0d5cabaaf27d2166003e47f56e671c9f3054577b
[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   LHS = N.getOperand(0);
649   RHS = N.getOperand(1);
650   CC  = N.getOperand(4);
651   return true;
652 }
653
654 /// Return true if this is a SetCC-equivalent operation with only one use.
655 /// If this is true, it allows the users to invert the operation for free when
656 /// it is profitable to do so.
657 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
658   SDValue N0, N1, N2;
659   if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
660     return true;
661   return false;
662 }
663
664 /// Returns true if N is a BUILD_VECTOR node whose
665 /// elements are all the same constant or undefined.
666 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
667   BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
668   if (!C)
669     return false;
670
671   APInt SplatUndef;
672   unsigned SplatBitSize;
673   bool HasAnyUndefs;
674   EVT EltVT = N->getValueType(0).getVectorElementType();
675   return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
676                              HasAnyUndefs) &&
677           EltVT.getSizeInBits() >= SplatBitSize);
678 }
679
680 // \brief Returns the SDNode if it is a constant BuildVector or constant.
681 static SDNode *isConstantBuildVectorOrConstantInt(SDValue N) {
682   if (isa<ConstantSDNode>(N))
683     return N.getNode();
684   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
685   if (BV && BV->isConstant())
686     return BV;
687   return nullptr;
688 }
689
690 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
691 // int.
692 static ConstantSDNode *isConstOrConstSplat(SDValue N) {
693   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
694     return CN;
695
696   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
697     BitVector UndefElements;
698     ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
699
700     // BuildVectors can truncate their operands. Ignore that case here.
701     // FIXME: We blindly ignore splats which include undef which is overly
702     // pessimistic.
703     if (CN && UndefElements.none() &&
704         CN->getValueType(0) == N.getValueType().getScalarType())
705       return CN;
706   }
707
708   return nullptr;
709 }
710
711 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
712 // float.
713 static ConstantFPSDNode *isConstOrConstSplatFP(SDValue N) {
714   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
715     return CN;
716
717   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
718     BitVector UndefElements;
719     ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
720
721     if (CN && UndefElements.none())
722       return CN;
723   }
724
725   return nullptr;
726 }
727
728 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
729                                     SDValue N0, SDValue N1) {
730   EVT VT = N0.getValueType();
731   if (N0.getOpcode() == Opc) {
732     if (SDNode *L = isConstantBuildVectorOrConstantInt(N0.getOperand(1))) {
733       if (SDNode *R = isConstantBuildVectorOrConstantInt(N1)) {
734         // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
735         SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, L, R);
736         if (!OpNode.getNode())
737           return SDValue();
738         return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
739       }
740       if (N0.hasOneUse()) {
741         // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
742         // use
743         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
744         if (!OpNode.getNode())
745           return SDValue();
746         AddToWorklist(OpNode.getNode());
747         return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
748       }
749     }
750   }
751
752   if (N1.getOpcode() == Opc) {
753     if (SDNode *R = isConstantBuildVectorOrConstantInt(N1.getOperand(1))) {
754       if (SDNode *L = isConstantBuildVectorOrConstantInt(N0)) {
755         // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
756         SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, R, L);
757         if (!OpNode.getNode())
758           return SDValue();
759         return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
760       }
761       if (N1.hasOneUse()) {
762         // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
763         // use
764         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
765         if (!OpNode.getNode())
766           return SDValue();
767         AddToWorklist(OpNode.getNode());
768         return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
769       }
770     }
771   }
772
773   return SDValue();
774 }
775
776 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
777                                bool AddTo) {
778   assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
779   ++NodesCombined;
780   DEBUG(dbgs() << "\nReplacing.1 ";
781         N->dump(&DAG);
782         dbgs() << "\nWith: ";
783         To[0].getNode()->dump(&DAG);
784         dbgs() << " and " << NumTo-1 << " other values\n";
785         for (unsigned i = 0, e = NumTo; i != e; ++i)
786           assert((!To[i].getNode() ||
787                   N->getValueType(i) == To[i].getValueType()) &&
788                  "Cannot combine value to value of different type!"));
789   WorklistRemover DeadNodes(*this);
790   DAG.ReplaceAllUsesWith(N, To);
791   if (AddTo) {
792     // Push the new nodes and any users onto the worklist
793     for (unsigned i = 0, e = NumTo; i != e; ++i) {
794       if (To[i].getNode()) {
795         AddToWorklist(To[i].getNode());
796         AddUsersToWorklist(To[i].getNode());
797       }
798     }
799   }
800
801   // Finally, if the node is now dead, remove it from the graph.  The node
802   // may not be dead if the replacement process recursively simplified to
803   // something else needing this node.
804   if (N->use_empty())
805     deleteAndRecombine(N);
806   return SDValue(N, 0);
807 }
808
809 void DAGCombiner::
810 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
811   // Replace all uses.  If any nodes become isomorphic to other nodes and
812   // are deleted, make sure to remove them from our worklist.
813   WorklistRemover DeadNodes(*this);
814   DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
815
816   // Push the new node and any (possibly new) users onto the worklist.
817   AddToWorklist(TLO.New.getNode());
818   AddUsersToWorklist(TLO.New.getNode());
819
820   // Finally, if the node is now dead, remove it from the graph.  The node
821   // may not be dead if the replacement process recursively simplified to
822   // something else needing this node.
823   if (TLO.Old.getNode()->use_empty())
824     deleteAndRecombine(TLO.Old.getNode());
825 }
826
827 /// Check the specified integer node value to see if it can be simplified or if
828 /// things it uses can be simplified by bit propagation. If so, return true.
829 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
830   TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
831   APInt KnownZero, KnownOne;
832   if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
833     return false;
834
835   // Revisit the node.
836   AddToWorklist(Op.getNode());
837
838   // Replace the old value with the new one.
839   ++NodesCombined;
840   DEBUG(dbgs() << "\nReplacing.2 ";
841         TLO.Old.getNode()->dump(&DAG);
842         dbgs() << "\nWith: ";
843         TLO.New.getNode()->dump(&DAG);
844         dbgs() << '\n');
845
846   CommitTargetLoweringOpt(TLO);
847   return true;
848 }
849
850 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
851   SDLoc dl(Load);
852   EVT VT = Load->getValueType(0);
853   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
854
855   DEBUG(dbgs() << "\nReplacing.9 ";
856         Load->dump(&DAG);
857         dbgs() << "\nWith: ";
858         Trunc.getNode()->dump(&DAG);
859         dbgs() << '\n');
860   WorklistRemover DeadNodes(*this);
861   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
862   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
863   deleteAndRecombine(Load);
864   AddToWorklist(Trunc.getNode());
865 }
866
867 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
868   Replace = false;
869   SDLoc dl(Op);
870   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
871     EVT MemVT = LD->getMemoryVT();
872     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
873       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
874                                                   : ISD::EXTLOAD)
875       : LD->getExtensionType();
876     Replace = true;
877     return DAG.getExtLoad(ExtType, dl, PVT,
878                           LD->getChain(), LD->getBasePtr(),
879                           MemVT, LD->getMemOperand());
880   }
881
882   unsigned Opc = Op.getOpcode();
883   switch (Opc) {
884   default: break;
885   case ISD::AssertSext:
886     return DAG.getNode(ISD::AssertSext, dl, PVT,
887                        SExtPromoteOperand(Op.getOperand(0), PVT),
888                        Op.getOperand(1));
889   case ISD::AssertZext:
890     return DAG.getNode(ISD::AssertZext, dl, PVT,
891                        ZExtPromoteOperand(Op.getOperand(0), PVT),
892                        Op.getOperand(1));
893   case ISD::Constant: {
894     unsigned ExtOpc =
895       Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
896     return DAG.getNode(ExtOpc, dl, PVT, Op);
897   }
898   }
899
900   if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
901     return SDValue();
902   return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
903 }
904
905 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
906   if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
907     return SDValue();
908   EVT OldVT = Op.getValueType();
909   SDLoc dl(Op);
910   bool Replace = false;
911   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
912   if (!NewOp.getNode())
913     return SDValue();
914   AddToWorklist(NewOp.getNode());
915
916   if (Replace)
917     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
918   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
919                      DAG.getValueType(OldVT));
920 }
921
922 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
923   EVT OldVT = Op.getValueType();
924   SDLoc dl(Op);
925   bool Replace = false;
926   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
927   if (!NewOp.getNode())
928     return SDValue();
929   AddToWorklist(NewOp.getNode());
930
931   if (Replace)
932     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
933   return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
934 }
935
936 /// Promote the specified integer binary operation if the target indicates it is
937 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
938 /// i32 since i16 instructions are longer.
939 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
940   if (!LegalOperations)
941     return SDValue();
942
943   EVT VT = Op.getValueType();
944   if (VT.isVector() || !VT.isInteger())
945     return SDValue();
946
947   // If operation type is 'undesirable', e.g. i16 on x86, consider
948   // promoting it.
949   unsigned Opc = Op.getOpcode();
950   if (TLI.isTypeDesirableForOp(Opc, VT))
951     return SDValue();
952
953   EVT PVT = VT;
954   // Consult target whether it is a good idea to promote this operation and
955   // what's the right type to promote it to.
956   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
957     assert(PVT != VT && "Don't know what type to promote to!");
958
959     bool Replace0 = false;
960     SDValue N0 = Op.getOperand(0);
961     SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
962     if (!NN0.getNode())
963       return SDValue();
964
965     bool Replace1 = false;
966     SDValue N1 = Op.getOperand(1);
967     SDValue NN1;
968     if (N0 == N1)
969       NN1 = NN0;
970     else {
971       NN1 = PromoteOperand(N1, PVT, Replace1);
972       if (!NN1.getNode())
973         return SDValue();
974     }
975
976     AddToWorklist(NN0.getNode());
977     if (NN1.getNode())
978       AddToWorklist(NN1.getNode());
979
980     if (Replace0)
981       ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
982     if (Replace1)
983       ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
984
985     DEBUG(dbgs() << "\nPromoting ";
986           Op.getNode()->dump(&DAG));
987     SDLoc dl(Op);
988     return DAG.getNode(ISD::TRUNCATE, dl, VT,
989                        DAG.getNode(Opc, dl, PVT, NN0, NN1));
990   }
991   return SDValue();
992 }
993
994 /// Promote the specified integer shift operation if the target indicates it is
995 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
996 /// i32 since i16 instructions are longer.
997 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
998   if (!LegalOperations)
999     return SDValue();
1000
1001   EVT VT = Op.getValueType();
1002   if (VT.isVector() || !VT.isInteger())
1003     return SDValue();
1004
1005   // If operation type is 'undesirable', e.g. i16 on x86, consider
1006   // promoting it.
1007   unsigned Opc = Op.getOpcode();
1008   if (TLI.isTypeDesirableForOp(Opc, VT))
1009     return SDValue();
1010
1011   EVT PVT = VT;
1012   // Consult target whether it is a good idea to promote this operation and
1013   // what's the right type to promote it to.
1014   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1015     assert(PVT != VT && "Don't know what type to promote to!");
1016
1017     bool Replace = false;
1018     SDValue N0 = Op.getOperand(0);
1019     if (Opc == ISD::SRA)
1020       N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
1021     else if (Opc == ISD::SRL)
1022       N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
1023     else
1024       N0 = PromoteOperand(N0, PVT, Replace);
1025     if (!N0.getNode())
1026       return SDValue();
1027
1028     AddToWorklist(N0.getNode());
1029     if (Replace)
1030       ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1031
1032     DEBUG(dbgs() << "\nPromoting ";
1033           Op.getNode()->dump(&DAG));
1034     SDLoc dl(Op);
1035     return DAG.getNode(ISD::TRUNCATE, dl, VT,
1036                        DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
1037   }
1038   return SDValue();
1039 }
1040
1041 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1042   if (!LegalOperations)
1043     return SDValue();
1044
1045   EVT VT = Op.getValueType();
1046   if (VT.isVector() || !VT.isInteger())
1047     return SDValue();
1048
1049   // If operation type is 'undesirable', e.g. i16 on x86, consider
1050   // promoting it.
1051   unsigned Opc = Op.getOpcode();
1052   if (TLI.isTypeDesirableForOp(Opc, VT))
1053     return SDValue();
1054
1055   EVT PVT = VT;
1056   // Consult target whether it is a good idea to promote this operation and
1057   // what's the right type to promote it to.
1058   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1059     assert(PVT != VT && "Don't know what type to promote to!");
1060     // fold (aext (aext x)) -> (aext x)
1061     // fold (aext (zext x)) -> (zext x)
1062     // fold (aext (sext x)) -> (sext x)
1063     DEBUG(dbgs() << "\nPromoting ";
1064           Op.getNode()->dump(&DAG));
1065     return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1066   }
1067   return SDValue();
1068 }
1069
1070 bool DAGCombiner::PromoteLoad(SDValue Op) {
1071   if (!LegalOperations)
1072     return false;
1073
1074   EVT VT = Op.getValueType();
1075   if (VT.isVector() || !VT.isInteger())
1076     return false;
1077
1078   // If operation type is 'undesirable', e.g. i16 on x86, consider
1079   // promoting it.
1080   unsigned Opc = Op.getOpcode();
1081   if (TLI.isTypeDesirableForOp(Opc, VT))
1082     return false;
1083
1084   EVT PVT = VT;
1085   // Consult target whether it is a good idea to promote this operation and
1086   // what's the right type to promote it to.
1087   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1088     assert(PVT != VT && "Don't know what type to promote to!");
1089
1090     SDLoc dl(Op);
1091     SDNode *N = Op.getNode();
1092     LoadSDNode *LD = cast<LoadSDNode>(N);
1093     EVT MemVT = LD->getMemoryVT();
1094     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1095       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
1096                                                   : ISD::EXTLOAD)
1097       : LD->getExtensionType();
1098     SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1099                                    LD->getChain(), LD->getBasePtr(),
1100                                    MemVT, LD->getMemOperand());
1101     SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1102
1103     DEBUG(dbgs() << "\nPromoting ";
1104           N->dump(&DAG);
1105           dbgs() << "\nTo: ";
1106           Result.getNode()->dump(&DAG);
1107           dbgs() << '\n');
1108     WorklistRemover DeadNodes(*this);
1109     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1110     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1111     deleteAndRecombine(N);
1112     AddToWorklist(Result.getNode());
1113     return true;
1114   }
1115   return false;
1116 }
1117
1118 /// \brief Recursively delete a node which has no uses and any operands for
1119 /// which it is the only use.
1120 ///
1121 /// Note that this both deletes the nodes and removes them from the worklist.
1122 /// It also adds any nodes who have had a user deleted to the worklist as they
1123 /// may now have only one use and subject to other combines.
1124 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1125   if (!N->use_empty())
1126     return false;
1127
1128   SmallSetVector<SDNode *, 16> Nodes;
1129   Nodes.insert(N);
1130   do {
1131     N = Nodes.pop_back_val();
1132     if (!N)
1133       continue;
1134
1135     if (N->use_empty()) {
1136       for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1137         Nodes.insert(N->getOperand(i).getNode());
1138
1139       removeFromWorklist(N);
1140       DAG.DeleteNode(N);
1141     } else {
1142       AddToWorklist(N);
1143     }
1144   } while (!Nodes.empty());
1145   return true;
1146 }
1147
1148 //===----------------------------------------------------------------------===//
1149 //  Main DAG Combiner implementation
1150 //===----------------------------------------------------------------------===//
1151
1152 void DAGCombiner::Run(CombineLevel AtLevel) {
1153   // set the instance variables, so that the various visit routines may use it.
1154   Level = AtLevel;
1155   LegalOperations = Level >= AfterLegalizeVectorOps;
1156   LegalTypes = Level >= AfterLegalizeTypes;
1157
1158   // Add all the dag nodes to the worklist.
1159   for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1160        E = DAG.allnodes_end(); I != E; ++I)
1161     AddToWorklist(I);
1162
1163   // Create a dummy node (which is not added to allnodes), that adds a reference
1164   // to the root node, preventing it from being deleted, and tracking any
1165   // changes of the root.
1166   HandleSDNode Dummy(DAG.getRoot());
1167
1168   // while the worklist isn't empty, find a node and
1169   // try and combine it.
1170   while (!WorklistMap.empty()) {
1171     SDNode *N;
1172     // The Worklist holds the SDNodes in order, but it may contain null entries.
1173     do {
1174       N = Worklist.pop_back_val();
1175     } while (!N);
1176
1177     bool GoodWorklistEntry = WorklistMap.erase(N);
1178     (void)GoodWorklistEntry;
1179     assert(GoodWorklistEntry &&
1180            "Found a worklist entry without a corresponding map entry!");
1181
1182     // If N has no uses, it is dead.  Make sure to revisit all N's operands once
1183     // N is deleted from the DAG, since they too may now be dead or may have a
1184     // reduced number of uses, allowing other xforms.
1185     if (recursivelyDeleteUnusedNodes(N))
1186       continue;
1187
1188     WorklistRemover DeadNodes(*this);
1189
1190     // If this combine is running after legalizing the DAG, re-legalize any
1191     // nodes pulled off the worklist.
1192     if (Level == AfterLegalizeDAG) {
1193       SmallSetVector<SDNode *, 16> UpdatedNodes;
1194       bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1195
1196       for (SDNode *LN : UpdatedNodes) {
1197         AddToWorklist(LN);
1198         AddUsersToWorklist(LN);
1199       }
1200       if (!NIsValid)
1201         continue;
1202     }
1203
1204     DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1205
1206     // Add any operands of the new node which have not yet been combined to the
1207     // worklist as well. Because the worklist uniques things already, this
1208     // won't repeatedly process the same operand.
1209     CombinedNodes.insert(N);
1210     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1211       if (!CombinedNodes.count(N->getOperand(i).getNode()))
1212         AddToWorklist(N->getOperand(i).getNode());
1213
1214     SDValue RV = combine(N);
1215
1216     if (!RV.getNode())
1217       continue;
1218
1219     ++NodesCombined;
1220
1221     // If we get back the same node we passed in, rather than a new node or
1222     // zero, we know that the node must have defined multiple values and
1223     // CombineTo was used.  Since CombineTo takes care of the worklist
1224     // mechanics for us, we have no work to do in this case.
1225     if (RV.getNode() == N)
1226       continue;
1227
1228     assert(N->getOpcode() != ISD::DELETED_NODE &&
1229            RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1230            "Node was deleted but visit returned new node!");
1231
1232     DEBUG(dbgs() << " ... into: ";
1233           RV.getNode()->dump(&DAG));
1234
1235     // Transfer debug value.
1236     DAG.TransferDbgValues(SDValue(N, 0), RV);
1237     if (N->getNumValues() == RV.getNode()->getNumValues())
1238       DAG.ReplaceAllUsesWith(N, RV.getNode());
1239     else {
1240       assert(N->getValueType(0) == RV.getValueType() &&
1241              N->getNumValues() == 1 && "Type mismatch");
1242       SDValue OpV = RV;
1243       DAG.ReplaceAllUsesWith(N, &OpV);
1244     }
1245
1246     // Push the new node and any users onto the worklist
1247     AddToWorklist(RV.getNode());
1248     AddUsersToWorklist(RV.getNode());
1249
1250     // Finally, if the node is now dead, remove it from the graph.  The node
1251     // may not be dead if the replacement process recursively simplified to
1252     // something else needing this node. This will also take care of adding any
1253     // operands which have lost a user to the worklist.
1254     recursivelyDeleteUnusedNodes(N);
1255   }
1256
1257   // If the root changed (e.g. it was a dead load, update the root).
1258   DAG.setRoot(Dummy.getValue());
1259   DAG.RemoveDeadNodes();
1260 }
1261
1262 SDValue DAGCombiner::visit(SDNode *N) {
1263   switch (N->getOpcode()) {
1264   default: break;
1265   case ISD::TokenFactor:        return visitTokenFactor(N);
1266   case ISD::MERGE_VALUES:       return visitMERGE_VALUES(N);
1267   case ISD::ADD:                return visitADD(N);
1268   case ISD::SUB:                return visitSUB(N);
1269   case ISD::ADDC:               return visitADDC(N);
1270   case ISD::SUBC:               return visitSUBC(N);
1271   case ISD::ADDE:               return visitADDE(N);
1272   case ISD::SUBE:               return visitSUBE(N);
1273   case ISD::MUL:                return visitMUL(N);
1274   case ISD::SDIV:               return visitSDIV(N);
1275   case ISD::UDIV:               return visitUDIV(N);
1276   case ISD::SREM:               return visitSREM(N);
1277   case ISD::UREM:               return visitUREM(N);
1278   case ISD::MULHU:              return visitMULHU(N);
1279   case ISD::MULHS:              return visitMULHS(N);
1280   case ISD::SMUL_LOHI:          return visitSMUL_LOHI(N);
1281   case ISD::UMUL_LOHI:          return visitUMUL_LOHI(N);
1282   case ISD::SMULO:              return visitSMULO(N);
1283   case ISD::UMULO:              return visitUMULO(N);
1284   case ISD::SDIVREM:            return visitSDIVREM(N);
1285   case ISD::UDIVREM:            return visitUDIVREM(N);
1286   case ISD::AND:                return visitAND(N);
1287   case ISD::OR:                 return visitOR(N);
1288   case ISD::XOR:                return visitXOR(N);
1289   case ISD::SHL:                return visitSHL(N);
1290   case ISD::SRA:                return visitSRA(N);
1291   case ISD::SRL:                return visitSRL(N);
1292   case ISD::ROTR:
1293   case ISD::ROTL:               return visitRotate(N);
1294   case ISD::CTLZ:               return visitCTLZ(N);
1295   case ISD::CTLZ_ZERO_UNDEF:    return visitCTLZ_ZERO_UNDEF(N);
1296   case ISD::CTTZ:               return visitCTTZ(N);
1297   case ISD::CTTZ_ZERO_UNDEF:    return visitCTTZ_ZERO_UNDEF(N);
1298   case ISD::CTPOP:              return visitCTPOP(N);
1299   case ISD::SELECT:             return visitSELECT(N);
1300   case ISD::VSELECT:            return visitVSELECT(N);
1301   case ISD::SELECT_CC:          return visitSELECT_CC(N);
1302   case ISD::SETCC:              return visitSETCC(N);
1303   case ISD::SIGN_EXTEND:        return visitSIGN_EXTEND(N);
1304   case ISD::ZERO_EXTEND:        return visitZERO_EXTEND(N);
1305   case ISD::ANY_EXTEND:         return visitANY_EXTEND(N);
1306   case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
1307   case ISD::TRUNCATE:           return visitTRUNCATE(N);
1308   case ISD::BITCAST:            return visitBITCAST(N);
1309   case ISD::BUILD_PAIR:         return visitBUILD_PAIR(N);
1310   case ISD::FADD:               return visitFADD(N);
1311   case ISD::FSUB:               return visitFSUB(N);
1312   case ISD::FMUL:               return visitFMUL(N);
1313   case ISD::FMA:                return visitFMA(N);
1314   case ISD::FDIV:               return visitFDIV(N);
1315   case ISD::FREM:               return visitFREM(N);
1316   case ISD::FSQRT:              return visitFSQRT(N);
1317   case ISD::FCOPYSIGN:          return visitFCOPYSIGN(N);
1318   case ISD::SINT_TO_FP:         return visitSINT_TO_FP(N);
1319   case ISD::UINT_TO_FP:         return visitUINT_TO_FP(N);
1320   case ISD::FP_TO_SINT:         return visitFP_TO_SINT(N);
1321   case ISD::FP_TO_UINT:         return visitFP_TO_UINT(N);
1322   case ISD::FP_ROUND:           return visitFP_ROUND(N);
1323   case ISD::FP_ROUND_INREG:     return visitFP_ROUND_INREG(N);
1324   case ISD::FP_EXTEND:          return visitFP_EXTEND(N);
1325   case ISD::FNEG:               return visitFNEG(N);
1326   case ISD::FABS:               return visitFABS(N);
1327   case ISD::FFLOOR:             return visitFFLOOR(N);
1328   case ISD::FMINNUM:            return visitFMINNUM(N);
1329   case ISD::FMAXNUM:            return visitFMAXNUM(N);
1330   case ISD::FCEIL:              return visitFCEIL(N);
1331   case ISD::FTRUNC:             return visitFTRUNC(N);
1332   case ISD::BRCOND:             return visitBRCOND(N);
1333   case ISD::BR_CC:              return visitBR_CC(N);
1334   case ISD::LOAD:               return visitLOAD(N);
1335   case ISD::STORE:              return visitSTORE(N);
1336   case ISD::INSERT_VECTOR_ELT:  return visitINSERT_VECTOR_ELT(N);
1337   case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1338   case ISD::BUILD_VECTOR:       return visitBUILD_VECTOR(N);
1339   case ISD::CONCAT_VECTORS:     return visitCONCAT_VECTORS(N);
1340   case ISD::EXTRACT_SUBVECTOR:  return visitEXTRACT_SUBVECTOR(N);
1341   case ISD::VECTOR_SHUFFLE:     return visitVECTOR_SHUFFLE(N);
1342   case ISD::INSERT_SUBVECTOR:   return visitINSERT_SUBVECTOR(N);
1343   }
1344   return SDValue();
1345 }
1346
1347 SDValue DAGCombiner::combine(SDNode *N) {
1348   SDValue RV = visit(N);
1349
1350   // If nothing happened, try a target-specific DAG combine.
1351   if (!RV.getNode()) {
1352     assert(N->getOpcode() != ISD::DELETED_NODE &&
1353            "Node was deleted but visit returned NULL!");
1354
1355     if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1356         TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1357
1358       // Expose the DAG combiner to the target combiner impls.
1359       TargetLowering::DAGCombinerInfo
1360         DagCombineInfo(DAG, Level, false, this);
1361
1362       RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1363     }
1364   }
1365
1366   // If nothing happened still, try promoting the operation.
1367   if (!RV.getNode()) {
1368     switch (N->getOpcode()) {
1369     default: break;
1370     case ISD::ADD:
1371     case ISD::SUB:
1372     case ISD::MUL:
1373     case ISD::AND:
1374     case ISD::OR:
1375     case ISD::XOR:
1376       RV = PromoteIntBinOp(SDValue(N, 0));
1377       break;
1378     case ISD::SHL:
1379     case ISD::SRA:
1380     case ISD::SRL:
1381       RV = PromoteIntShiftOp(SDValue(N, 0));
1382       break;
1383     case ISD::SIGN_EXTEND:
1384     case ISD::ZERO_EXTEND:
1385     case ISD::ANY_EXTEND:
1386       RV = PromoteExtend(SDValue(N, 0));
1387       break;
1388     case ISD::LOAD:
1389       if (PromoteLoad(SDValue(N, 0)))
1390         RV = SDValue(N, 0);
1391       break;
1392     }
1393   }
1394
1395   // If N is a commutative binary node, try commuting it to enable more
1396   // sdisel CSE.
1397   if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1398       N->getNumValues() == 1) {
1399     SDValue N0 = N->getOperand(0);
1400     SDValue N1 = N->getOperand(1);
1401
1402     // Constant operands are canonicalized to RHS.
1403     if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1404       SDValue Ops[] = {N1, N0};
1405       SDNode *CSENode;
1406       if (const BinaryWithFlagsSDNode *BinNode =
1407               dyn_cast<BinaryWithFlagsSDNode>(N)) {
1408         CSENode = DAG.getNodeIfExists(
1409             N->getOpcode(), N->getVTList(), Ops, BinNode->hasNoUnsignedWrap(),
1410             BinNode->hasNoSignedWrap(), BinNode->isExact());
1411       } else {
1412         CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops);
1413       }
1414       if (CSENode)
1415         return SDValue(CSENode, 0);
1416     }
1417   }
1418
1419   return RV;
1420 }
1421
1422 /// Given a node, return its input chain if it has one, otherwise return a null
1423 /// sd operand.
1424 static SDValue getInputChainForNode(SDNode *N) {
1425   if (unsigned NumOps = N->getNumOperands()) {
1426     if (N->getOperand(0).getValueType() == MVT::Other)
1427       return N->getOperand(0);
1428     if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1429       return N->getOperand(NumOps-1);
1430     for (unsigned i = 1; i < NumOps-1; ++i)
1431       if (N->getOperand(i).getValueType() == MVT::Other)
1432         return N->getOperand(i);
1433   }
1434   return SDValue();
1435 }
1436
1437 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1438   // If N has two operands, where one has an input chain equal to the other,
1439   // the 'other' chain is redundant.
1440   if (N->getNumOperands() == 2) {
1441     if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1442       return N->getOperand(0);
1443     if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1444       return N->getOperand(1);
1445   }
1446
1447   SmallVector<SDNode *, 8> TFs;     // List of token factors to visit.
1448   SmallVector<SDValue, 8> Ops;    // Ops for replacing token factor.
1449   SmallPtrSet<SDNode*, 16> SeenOps;
1450   bool Changed = false;             // If we should replace this token factor.
1451
1452   // Start out with this token factor.
1453   TFs.push_back(N);
1454
1455   // Iterate through token factors.  The TFs grows when new token factors are
1456   // encountered.
1457   for (unsigned i = 0; i < TFs.size(); ++i) {
1458     SDNode *TF = TFs[i];
1459
1460     // Check each of the operands.
1461     for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1462       SDValue Op = TF->getOperand(i);
1463
1464       switch (Op.getOpcode()) {
1465       case ISD::EntryToken:
1466         // Entry tokens don't need to be added to the list. They are
1467         // rededundant.
1468         Changed = true;
1469         break;
1470
1471       case ISD::TokenFactor:
1472         if (Op.hasOneUse() &&
1473             std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1474           // Queue up for processing.
1475           TFs.push_back(Op.getNode());
1476           // Clean up in case the token factor is removed.
1477           AddToWorklist(Op.getNode());
1478           Changed = true;
1479           break;
1480         }
1481         // Fall thru
1482
1483       default:
1484         // Only add if it isn't already in the list.
1485         if (SeenOps.insert(Op.getNode()))
1486           Ops.push_back(Op);
1487         else
1488           Changed = true;
1489         break;
1490       }
1491     }
1492   }
1493
1494   SDValue Result;
1495
1496   // If we've change things around then replace token factor.
1497   if (Changed) {
1498     if (Ops.empty()) {
1499       // The entry token is the only possible outcome.
1500       Result = DAG.getEntryNode();
1501     } else {
1502       // New and improved token factor.
1503       Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1504     }
1505
1506     // Don't add users to work list.
1507     return CombineTo(N, Result, false);
1508   }
1509
1510   return Result;
1511 }
1512
1513 /// MERGE_VALUES can always be eliminated.
1514 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1515   WorklistRemover DeadNodes(*this);
1516   // Replacing results may cause a different MERGE_VALUES to suddenly
1517   // be CSE'd with N, and carry its uses with it. Iterate until no
1518   // uses remain, to ensure that the node can be safely deleted.
1519   // First add the users of this node to the work list so that they
1520   // can be tried again once they have new operands.
1521   AddUsersToWorklist(N);
1522   do {
1523     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1524       DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1525   } while (!N->use_empty());
1526   deleteAndRecombine(N);
1527   return SDValue(N, 0);   // Return N so it doesn't get rechecked!
1528 }
1529
1530 SDValue DAGCombiner::visitADD(SDNode *N) {
1531   SDValue N0 = N->getOperand(0);
1532   SDValue N1 = N->getOperand(1);
1533   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1534   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1535   EVT VT = N0.getValueType();
1536
1537   // fold vector ops
1538   if (VT.isVector()) {
1539     SDValue FoldedVOp = SimplifyVBinOp(N);
1540     if (FoldedVOp.getNode()) return FoldedVOp;
1541
1542     // fold (add x, 0) -> x, vector edition
1543     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1544       return N0;
1545     if (ISD::isBuildVectorAllZeros(N0.getNode()))
1546       return N1;
1547   }
1548
1549   // fold (add x, undef) -> undef
1550   if (N0.getOpcode() == ISD::UNDEF)
1551     return N0;
1552   if (N1.getOpcode() == ISD::UNDEF)
1553     return N1;
1554   // fold (add c1, c2) -> c1+c2
1555   if (N0C && N1C)
1556     return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
1557   // canonicalize constant to RHS
1558   if (N0C && !N1C)
1559     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1560   // fold (add x, 0) -> x
1561   if (N1C && N1C->isNullValue())
1562     return N0;
1563   // fold (add Sym, c) -> Sym+c
1564   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1565     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1566         GA->getOpcode() == ISD::GlobalAddress)
1567       return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1568                                   GA->getOffset() +
1569                                     (uint64_t)N1C->getSExtValue());
1570   // fold ((c1-A)+c2) -> (c1+c2)-A
1571   if (N1C && N0.getOpcode() == ISD::SUB)
1572     if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
1573       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1574                          DAG.getConstant(N1C->getAPIntValue()+
1575                                          N0C->getAPIntValue(), VT),
1576                          N0.getOperand(1));
1577   // reassociate add
1578   SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1);
1579   if (RADD.getNode())
1580     return RADD;
1581   // fold ((0-A) + B) -> B-A
1582   if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1583       cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1584     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1585   // fold (A + (0-B)) -> A-B
1586   if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1587       cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1588     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1589   // fold (A+(B-A)) -> B
1590   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1591     return N1.getOperand(0);
1592   // fold ((B-A)+A) -> B
1593   if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1594     return N0.getOperand(0);
1595   // fold (A+(B-(A+C))) to (B-C)
1596   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1597       N0 == N1.getOperand(1).getOperand(0))
1598     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1599                        N1.getOperand(1).getOperand(1));
1600   // fold (A+(B-(C+A))) to (B-C)
1601   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1602       N0 == N1.getOperand(1).getOperand(1))
1603     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1604                        N1.getOperand(1).getOperand(0));
1605   // fold (A+((B-A)+or-C)) to (B+or-C)
1606   if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1607       N1.getOperand(0).getOpcode() == ISD::SUB &&
1608       N0 == N1.getOperand(0).getOperand(1))
1609     return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1610                        N1.getOperand(0).getOperand(0), N1.getOperand(1));
1611
1612   // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1613   if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1614     SDValue N00 = N0.getOperand(0);
1615     SDValue N01 = N0.getOperand(1);
1616     SDValue N10 = N1.getOperand(0);
1617     SDValue N11 = N1.getOperand(1);
1618
1619     if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1620       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1621                          DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1622                          DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1623   }
1624
1625   if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1626     return SDValue(N, 0);
1627
1628   // fold (a+b) -> (a|b) iff a and b share no bits.
1629   if (VT.isInteger() && !VT.isVector()) {
1630     APInt LHSZero, LHSOne;
1631     APInt RHSZero, RHSOne;
1632     DAG.computeKnownBits(N0, LHSZero, LHSOne);
1633
1634     if (LHSZero.getBoolValue()) {
1635       DAG.computeKnownBits(N1, RHSZero, RHSOne);
1636
1637       // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1638       // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1639       if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1640         if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1641           return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1642       }
1643     }
1644   }
1645
1646   // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1647   if (N1.getOpcode() == ISD::SHL &&
1648       N1.getOperand(0).getOpcode() == ISD::SUB)
1649     if (ConstantSDNode *C =
1650           dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1651       if (C->getAPIntValue() == 0)
1652         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1653                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
1654                                        N1.getOperand(0).getOperand(1),
1655                                        N1.getOperand(1)));
1656   if (N0.getOpcode() == ISD::SHL &&
1657       N0.getOperand(0).getOpcode() == ISD::SUB)
1658     if (ConstantSDNode *C =
1659           dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1660       if (C->getAPIntValue() == 0)
1661         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1662                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
1663                                        N0.getOperand(0).getOperand(1),
1664                                        N0.getOperand(1)));
1665
1666   if (N1.getOpcode() == ISD::AND) {
1667     SDValue AndOp0 = N1.getOperand(0);
1668     ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1669     unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1670     unsigned DestBits = VT.getScalarType().getSizeInBits();
1671
1672     // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1673     // and similar xforms where the inner op is either ~0 or 0.
1674     if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1675       SDLoc DL(N);
1676       return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1677     }
1678   }
1679
1680   // add (sext i1), X -> sub X, (zext i1)
1681   if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1682       N0.getOperand(0).getValueType() == MVT::i1 &&
1683       !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1684     SDLoc DL(N);
1685     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1686     return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1687   }
1688
1689   // add X, (sextinreg Y i1) -> sub X, (and Y 1)
1690   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1691     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1692     if (TN->getVT() == MVT::i1) {
1693       SDLoc DL(N);
1694       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1695                                  DAG.getConstant(1, VT));
1696       return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
1697     }
1698   }
1699
1700   return SDValue();
1701 }
1702
1703 SDValue DAGCombiner::visitADDC(SDNode *N) {
1704   SDValue N0 = N->getOperand(0);
1705   SDValue N1 = N->getOperand(1);
1706   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1707   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1708   EVT VT = N0.getValueType();
1709
1710   // If the flag result is dead, turn this into an ADD.
1711   if (!N->hasAnyUseOfValue(1))
1712     return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1713                      DAG.getNode(ISD::CARRY_FALSE,
1714                                  SDLoc(N), MVT::Glue));
1715
1716   // canonicalize constant to RHS.
1717   if (N0C && !N1C)
1718     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1719
1720   // fold (addc x, 0) -> x + no carry out
1721   if (N1C && N1C->isNullValue())
1722     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1723                                         SDLoc(N), MVT::Glue));
1724
1725   // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1726   APInt LHSZero, LHSOne;
1727   APInt RHSZero, RHSOne;
1728   DAG.computeKnownBits(N0, LHSZero, LHSOne);
1729
1730   if (LHSZero.getBoolValue()) {
1731     DAG.computeKnownBits(N1, RHSZero, RHSOne);
1732
1733     // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1734     // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1735     if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1736       return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1737                        DAG.getNode(ISD::CARRY_FALSE,
1738                                    SDLoc(N), MVT::Glue));
1739   }
1740
1741   return SDValue();
1742 }
1743
1744 SDValue DAGCombiner::visitADDE(SDNode *N) {
1745   SDValue N0 = N->getOperand(0);
1746   SDValue N1 = N->getOperand(1);
1747   SDValue CarryIn = N->getOperand(2);
1748   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1749   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1750
1751   // canonicalize constant to RHS
1752   if (N0C && !N1C)
1753     return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1754                        N1, N0, CarryIn);
1755
1756   // fold (adde x, y, false) -> (addc x, y)
1757   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1758     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1759
1760   return SDValue();
1761 }
1762
1763 // Since it may not be valid to emit a fold to zero for vector initializers
1764 // check if we can before folding.
1765 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1766                              SelectionDAG &DAG,
1767                              bool LegalOperations, bool LegalTypes) {
1768   if (!VT.isVector())
1769     return DAG.getConstant(0, VT);
1770   if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1771     return DAG.getConstant(0, VT);
1772   return SDValue();
1773 }
1774
1775 SDValue DAGCombiner::visitSUB(SDNode *N) {
1776   SDValue N0 = N->getOperand(0);
1777   SDValue N1 = N->getOperand(1);
1778   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1779   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1780   ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1781     dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1782   EVT VT = N0.getValueType();
1783
1784   // fold vector ops
1785   if (VT.isVector()) {
1786     SDValue FoldedVOp = SimplifyVBinOp(N);
1787     if (FoldedVOp.getNode()) return FoldedVOp;
1788
1789     // fold (sub x, 0) -> x, vector edition
1790     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1791       return N0;
1792   }
1793
1794   // fold (sub x, x) -> 0
1795   // FIXME: Refactor this and xor and other similar operations together.
1796   if (N0 == N1)
1797     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1798   // fold (sub c1, c2) -> c1-c2
1799   if (N0C && N1C)
1800     return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1801   // fold (sub x, c) -> (add x, -c)
1802   if (N1C)
1803     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
1804                        DAG.getConstant(-N1C->getAPIntValue(), VT));
1805   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1806   if (N0C && N0C->isAllOnesValue())
1807     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1808   // fold A-(A-B) -> B
1809   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1810     return N1.getOperand(1);
1811   // fold (A+B)-A -> B
1812   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1813     return N0.getOperand(1);
1814   // fold (A+B)-B -> A
1815   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1816     return N0.getOperand(0);
1817   // fold C2-(A+C1) -> (C2-C1)-A
1818   if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1819     SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1820                                    VT);
1821     return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
1822                        N1.getOperand(0));
1823   }
1824   // fold ((A+(B+or-C))-B) -> A+or-C
1825   if (N0.getOpcode() == ISD::ADD &&
1826       (N0.getOperand(1).getOpcode() == ISD::SUB ||
1827        N0.getOperand(1).getOpcode() == ISD::ADD) &&
1828       N0.getOperand(1).getOperand(0) == N1)
1829     return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1830                        N0.getOperand(0), N0.getOperand(1).getOperand(1));
1831   // fold ((A+(C+B))-B) -> A+C
1832   if (N0.getOpcode() == ISD::ADD &&
1833       N0.getOperand(1).getOpcode() == ISD::ADD &&
1834       N0.getOperand(1).getOperand(1) == N1)
1835     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1836                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1837   // fold ((A-(B-C))-C) -> A-B
1838   if (N0.getOpcode() == ISD::SUB &&
1839       N0.getOperand(1).getOpcode() == ISD::SUB &&
1840       N0.getOperand(1).getOperand(1) == N1)
1841     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1842                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1843
1844   // If either operand of a sub is undef, the result is undef
1845   if (N0.getOpcode() == ISD::UNDEF)
1846     return N0;
1847   if (N1.getOpcode() == ISD::UNDEF)
1848     return N1;
1849
1850   // If the relocation model supports it, consider symbol offsets.
1851   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1852     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1853       // fold (sub Sym, c) -> Sym-c
1854       if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1855         return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1856                                     GA->getOffset() -
1857                                       (uint64_t)N1C->getSExtValue());
1858       // fold (sub Sym+c1, Sym+c2) -> c1-c2
1859       if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1860         if (GA->getGlobal() == GB->getGlobal())
1861           return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1862                                  VT);
1863     }
1864
1865   // sub X, (sextinreg Y i1) -> add X, (and Y 1)
1866   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1867     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1868     if (TN->getVT() == MVT::i1) {
1869       SDLoc DL(N);
1870       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1871                                  DAG.getConstant(1, VT));
1872       return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
1873     }
1874   }
1875
1876   return SDValue();
1877 }
1878
1879 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1880   SDValue N0 = N->getOperand(0);
1881   SDValue N1 = N->getOperand(1);
1882   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1883   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1884   EVT VT = N0.getValueType();
1885
1886   // If the flag result is dead, turn this into an SUB.
1887   if (!N->hasAnyUseOfValue(1))
1888     return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1889                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1890                                  MVT::Glue));
1891
1892   // fold (subc x, x) -> 0 + no borrow
1893   if (N0 == N1)
1894     return CombineTo(N, DAG.getConstant(0, VT),
1895                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1896                                  MVT::Glue));
1897
1898   // fold (subc x, 0) -> x + no borrow
1899   if (N1C && N1C->isNullValue())
1900     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1901                                         MVT::Glue));
1902
1903   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1904   if (N0C && N0C->isAllOnesValue())
1905     return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1906                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1907                                  MVT::Glue));
1908
1909   return SDValue();
1910 }
1911
1912 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1913   SDValue N0 = N->getOperand(0);
1914   SDValue N1 = N->getOperand(1);
1915   SDValue CarryIn = N->getOperand(2);
1916
1917   // fold (sube x, y, false) -> (subc x, y)
1918   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1919     return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
1920
1921   return SDValue();
1922 }
1923
1924 SDValue DAGCombiner::visitMUL(SDNode *N) {
1925   SDValue N0 = N->getOperand(0);
1926   SDValue N1 = N->getOperand(1);
1927   EVT VT = N0.getValueType();
1928
1929   // fold (mul x, undef) -> 0
1930   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1931     return DAG.getConstant(0, VT);
1932
1933   bool N0IsConst = false;
1934   bool N1IsConst = false;
1935   APInt ConstValue0, ConstValue1;
1936   // fold vector ops
1937   if (VT.isVector()) {
1938     SDValue FoldedVOp = SimplifyVBinOp(N);
1939     if (FoldedVOp.getNode()) return FoldedVOp;
1940
1941     N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1942     N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1943   } else {
1944     N0IsConst = dyn_cast<ConstantSDNode>(N0) != nullptr;
1945     ConstValue0 = N0IsConst ? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue()
1946                             : APInt();
1947     N1IsConst = dyn_cast<ConstantSDNode>(N1) != nullptr;
1948     ConstValue1 = N1IsConst ? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue()
1949                             : APInt();
1950   }
1951
1952   // fold (mul c1, c2) -> c1*c2
1953   if (N0IsConst && N1IsConst)
1954     return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
1955
1956   // canonicalize constant to RHS
1957   if (N0IsConst && !N1IsConst)
1958     return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
1959   // fold (mul x, 0) -> 0
1960   if (N1IsConst && ConstValue1 == 0)
1961     return N1;
1962   // We require a splat of the entire scalar bit width for non-contiguous
1963   // bit patterns.
1964   bool IsFullSplat =
1965     ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
1966   // fold (mul x, 1) -> x
1967   if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
1968     return N0;
1969   // fold (mul x, -1) -> 0-x
1970   if (N1IsConst && ConstValue1.isAllOnesValue())
1971     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1972                        DAG.getConstant(0, VT), N0);
1973   // fold (mul x, (1 << c)) -> x << c
1974   if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat)
1975     return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1976                        DAG.getConstant(ConstValue1.logBase2(),
1977                                        getShiftAmountTy(N0.getValueType())));
1978   // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1979   if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
1980     unsigned Log2Val = (-ConstValue1).logBase2();
1981     // FIXME: If the input is something that is easily negated (e.g. a
1982     // single-use add), we should put the negate there.
1983     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1984                        DAG.getConstant(0, VT),
1985                        DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1986                             DAG.getConstant(Log2Val,
1987                                       getShiftAmountTy(N0.getValueType()))));
1988   }
1989
1990   APInt Val;
1991   // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
1992   if (N1IsConst && N0.getOpcode() == ISD::SHL &&
1993       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1994                      isa<ConstantSDNode>(N0.getOperand(1)))) {
1995     SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
1996                              N1, N0.getOperand(1));
1997     AddToWorklist(C3.getNode());
1998     return DAG.getNode(ISD::MUL, SDLoc(N), VT,
1999                        N0.getOperand(0), C3);
2000   }
2001
2002   // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2003   // use.
2004   {
2005     SDValue Sh(nullptr,0), Y(nullptr,0);
2006     // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
2007     if (N0.getOpcode() == ISD::SHL &&
2008         (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2009                        isa<ConstantSDNode>(N0.getOperand(1))) &&
2010         N0.getNode()->hasOneUse()) {
2011       Sh = N0; Y = N1;
2012     } else if (N1.getOpcode() == ISD::SHL &&
2013                isa<ConstantSDNode>(N1.getOperand(1)) &&
2014                N1.getNode()->hasOneUse()) {
2015       Sh = N1; Y = N0;
2016     }
2017
2018     if (Sh.getNode()) {
2019       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2020                                 Sh.getOperand(0), Y);
2021       return DAG.getNode(ISD::SHL, SDLoc(N), VT,
2022                          Mul, Sh.getOperand(1));
2023     }
2024   }
2025
2026   // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2027   if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
2028       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2029                      isa<ConstantSDNode>(N0.getOperand(1))))
2030     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2031                        DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2032                                    N0.getOperand(0), N1),
2033                        DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2034                                    N0.getOperand(1), N1));
2035
2036   // reassociate mul
2037   SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1);
2038   if (RMUL.getNode())
2039     return RMUL;
2040
2041   return SDValue();
2042 }
2043
2044 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2045   SDValue N0 = N->getOperand(0);
2046   SDValue N1 = N->getOperand(1);
2047   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2048   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2049   EVT VT = N->getValueType(0);
2050
2051   // fold vector ops
2052   if (VT.isVector()) {
2053     SDValue FoldedVOp = SimplifyVBinOp(N);
2054     if (FoldedVOp.getNode()) return FoldedVOp;
2055   }
2056
2057   // fold (sdiv c1, c2) -> c1/c2
2058   if (N0C && N1C && !N1C->isNullValue())
2059     return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
2060   // fold (sdiv X, 1) -> X
2061   if (N1C && N1C->getAPIntValue() == 1LL)
2062     return N0;
2063   // fold (sdiv X, -1) -> 0-X
2064   if (N1C && N1C->isAllOnesValue())
2065     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
2066                        DAG.getConstant(0, VT), N0);
2067   // If we know the sign bits of both operands are zero, strength reduce to a
2068   // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
2069   if (!VT.isVector()) {
2070     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2071       return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
2072                          N0, N1);
2073   }
2074
2075   // fold (sdiv X, pow2) -> simple ops after legalize
2076   if (N1C && !N1C->isNullValue() && (N1C->getAPIntValue().isPowerOf2() ||
2077                                      (-N1C->getAPIntValue()).isPowerOf2())) {
2078     // If dividing by powers of two is cheap, then don't perform the following
2079     // fold.
2080     if (TLI.isPow2SDivCheap())
2081       return SDValue();
2082
2083     // Target-specific implementation of sdiv x, pow2.
2084     SDValue Res = BuildSDIVPow2(N);
2085     if (Res.getNode())
2086       return Res;
2087
2088     unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2089
2090     // Splat the sign bit into the register
2091     SDValue SGN =
2092         DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
2093                     DAG.getConstant(VT.getScalarSizeInBits() - 1,
2094                                     getShiftAmountTy(N0.getValueType())));
2095     AddToWorklist(SGN.getNode());
2096
2097     // Add (N0 < 0) ? abs2 - 1 : 0;
2098     SDValue SRL =
2099         DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
2100                     DAG.getConstant(VT.getScalarSizeInBits() - lg2,
2101                                     getShiftAmountTy(SGN.getValueType())));
2102     SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
2103     AddToWorklist(SRL.getNode());
2104     AddToWorklist(ADD.getNode());    // Divide by pow2
2105     SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
2106                   DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
2107
2108     // If we're dividing by a positive value, we're done.  Otherwise, we must
2109     // negate the result.
2110     if (N1C->getAPIntValue().isNonNegative())
2111       return SRA;
2112
2113     AddToWorklist(SRA.getNode());
2114     return DAG.getNode(ISD::SUB, SDLoc(N), VT, DAG.getConstant(0, VT), SRA);
2115   }
2116
2117   // if integer divide is expensive and we satisfy the requirements, emit an
2118   // alternate sequence.
2119   if (N1C && !TLI.isIntDivCheap()) {
2120     SDValue Op = BuildSDIV(N);
2121     if (Op.getNode()) return Op;
2122   }
2123
2124   // undef / X -> 0
2125   if (N0.getOpcode() == ISD::UNDEF)
2126     return DAG.getConstant(0, VT);
2127   // X / undef -> undef
2128   if (N1.getOpcode() == ISD::UNDEF)
2129     return N1;
2130
2131   return SDValue();
2132 }
2133
2134 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2135   SDValue N0 = N->getOperand(0);
2136   SDValue N1 = N->getOperand(1);
2137   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2138   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2139   EVT VT = N->getValueType(0);
2140
2141   // fold vector ops
2142   if (VT.isVector()) {
2143     SDValue FoldedVOp = SimplifyVBinOp(N);
2144     if (FoldedVOp.getNode()) return FoldedVOp;
2145   }
2146
2147   // fold (udiv c1, c2) -> c1/c2
2148   if (N0C && N1C && !N1C->isNullValue())
2149     return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
2150   // fold (udiv x, (1 << c)) -> x >>u c
2151   if (N1C && N1C->getAPIntValue().isPowerOf2())
2152     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
2153                        DAG.getConstant(N1C->getAPIntValue().logBase2(),
2154                                        getShiftAmountTy(N0.getValueType())));
2155   // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2156   if (N1.getOpcode() == ISD::SHL) {
2157     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2158       if (SHC->getAPIntValue().isPowerOf2()) {
2159         EVT ADDVT = N1.getOperand(1).getValueType();
2160         SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
2161                                   N1.getOperand(1),
2162                                   DAG.getConstant(SHC->getAPIntValue()
2163                                                                   .logBase2(),
2164                                                   ADDVT));
2165         AddToWorklist(Add.getNode());
2166         return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
2167       }
2168     }
2169   }
2170   // fold (udiv x, c) -> alternate
2171   if (N1C && !TLI.isIntDivCheap()) {
2172     SDValue Op = BuildUDIV(N);
2173     if (Op.getNode()) return Op;
2174   }
2175
2176   // undef / X -> 0
2177   if (N0.getOpcode() == ISD::UNDEF)
2178     return DAG.getConstant(0, VT);
2179   // X / undef -> undef
2180   if (N1.getOpcode() == ISD::UNDEF)
2181     return N1;
2182
2183   return SDValue();
2184 }
2185
2186 SDValue DAGCombiner::visitSREM(SDNode *N) {
2187   SDValue N0 = N->getOperand(0);
2188   SDValue N1 = N->getOperand(1);
2189   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2190   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2191   EVT VT = N->getValueType(0);
2192
2193   // fold (srem c1, c2) -> c1%c2
2194   if (N0C && N1C && !N1C->isNullValue())
2195     return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
2196   // If we know the sign bits of both operands are zero, strength reduce to a
2197   // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2198   if (!VT.isVector()) {
2199     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2200       return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2201   }
2202
2203   // If X/C can be simplified by the division-by-constant logic, lower
2204   // X%C to the equivalent of X-X/C*C.
2205   if (N1C && !N1C->isNullValue()) {
2206     SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2207     AddToWorklist(Div.getNode());
2208     SDValue OptimizedDiv = combine(Div.getNode());
2209     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2210       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2211                                 OptimizedDiv, N1);
2212       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2213       AddToWorklist(Mul.getNode());
2214       return Sub;
2215     }
2216   }
2217
2218   // undef % X -> 0
2219   if (N0.getOpcode() == ISD::UNDEF)
2220     return DAG.getConstant(0, VT);
2221   // X % undef -> undef
2222   if (N1.getOpcode() == ISD::UNDEF)
2223     return N1;
2224
2225   return SDValue();
2226 }
2227
2228 SDValue DAGCombiner::visitUREM(SDNode *N) {
2229   SDValue N0 = N->getOperand(0);
2230   SDValue N1 = N->getOperand(1);
2231   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2232   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2233   EVT VT = N->getValueType(0);
2234
2235   // fold (urem c1, c2) -> c1%c2
2236   if (N0C && N1C && !N1C->isNullValue())
2237     return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
2238   // fold (urem x, pow2) -> (and x, pow2-1)
2239   if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
2240     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
2241                        DAG.getConstant(N1C->getAPIntValue()-1,VT));
2242   // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2243   if (N1.getOpcode() == ISD::SHL) {
2244     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2245       if (SHC->getAPIntValue().isPowerOf2()) {
2246         SDValue Add =
2247           DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
2248                  DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
2249                                  VT));
2250         AddToWorklist(Add.getNode());
2251         return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
2252       }
2253     }
2254   }
2255
2256   // If X/C can be simplified by the division-by-constant logic, lower
2257   // X%C to the equivalent of X-X/C*C.
2258   if (N1C && !N1C->isNullValue()) {
2259     SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2260     AddToWorklist(Div.getNode());
2261     SDValue OptimizedDiv = combine(Div.getNode());
2262     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2263       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2264                                 OptimizedDiv, N1);
2265       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2266       AddToWorklist(Mul.getNode());
2267       return Sub;
2268     }
2269   }
2270
2271   // undef % X -> 0
2272   if (N0.getOpcode() == ISD::UNDEF)
2273     return DAG.getConstant(0, VT);
2274   // X % undef -> undef
2275   if (N1.getOpcode() == ISD::UNDEF)
2276     return N1;
2277
2278   return SDValue();
2279 }
2280
2281 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2282   SDValue N0 = N->getOperand(0);
2283   SDValue N1 = N->getOperand(1);
2284   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2285   EVT VT = N->getValueType(0);
2286   SDLoc DL(N);
2287
2288   // fold (mulhs x, 0) -> 0
2289   if (N1C && N1C->isNullValue())
2290     return N1;
2291   // fold (mulhs x, 1) -> (sra x, size(x)-1)
2292   if (N1C && N1C->getAPIntValue() == 1)
2293     return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
2294                        DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2295                                        getShiftAmountTy(N0.getValueType())));
2296   // fold (mulhs x, undef) -> 0
2297   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2298     return DAG.getConstant(0, VT);
2299
2300   // If the type twice as wide is legal, transform the mulhs to a wider multiply
2301   // plus a shift.
2302   if (VT.isSimple() && !VT.isVector()) {
2303     MVT Simple = VT.getSimpleVT();
2304     unsigned SimpleSize = Simple.getSizeInBits();
2305     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2306     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2307       N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2308       N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2309       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2310       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2311             DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2312       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2313     }
2314   }
2315
2316   return SDValue();
2317 }
2318
2319 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2320   SDValue N0 = N->getOperand(0);
2321   SDValue N1 = N->getOperand(1);
2322   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2323   EVT VT = N->getValueType(0);
2324   SDLoc DL(N);
2325
2326   // fold (mulhu x, 0) -> 0
2327   if (N1C && N1C->isNullValue())
2328     return N1;
2329   // fold (mulhu x, 1) -> 0
2330   if (N1C && N1C->getAPIntValue() == 1)
2331     return DAG.getConstant(0, N0.getValueType());
2332   // fold (mulhu x, undef) -> 0
2333   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2334     return DAG.getConstant(0, VT);
2335
2336   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2337   // plus a shift.
2338   if (VT.isSimple() && !VT.isVector()) {
2339     MVT Simple = VT.getSimpleVT();
2340     unsigned SimpleSize = Simple.getSizeInBits();
2341     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2342     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2343       N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2344       N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2345       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2346       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2347             DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2348       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2349     }
2350   }
2351
2352   return SDValue();
2353 }
2354
2355 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
2356 /// give the opcodes for the two computations that are being performed. Return
2357 /// true if a simplification was made.
2358 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2359                                                 unsigned HiOp) {
2360   // If the high half is not needed, just compute the low half.
2361   bool HiExists = N->hasAnyUseOfValue(1);
2362   if (!HiExists &&
2363       (!LegalOperations ||
2364        TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2365     SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2366     return CombineTo(N, Res, Res);
2367   }
2368
2369   // If the low half is not needed, just compute the high half.
2370   bool LoExists = N->hasAnyUseOfValue(0);
2371   if (!LoExists &&
2372       (!LegalOperations ||
2373        TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2374     SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2375     return CombineTo(N, Res, Res);
2376   }
2377
2378   // If both halves are used, return as it is.
2379   if (LoExists && HiExists)
2380     return SDValue();
2381
2382   // If the two computed results can be simplified separately, separate them.
2383   if (LoExists) {
2384     SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2385     AddToWorklist(Lo.getNode());
2386     SDValue LoOpt = combine(Lo.getNode());
2387     if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2388         (!LegalOperations ||
2389          TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2390       return CombineTo(N, LoOpt, LoOpt);
2391   }
2392
2393   if (HiExists) {
2394     SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2395     AddToWorklist(Hi.getNode());
2396     SDValue HiOpt = combine(Hi.getNode());
2397     if (HiOpt.getNode() && HiOpt != Hi &&
2398         (!LegalOperations ||
2399          TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2400       return CombineTo(N, HiOpt, HiOpt);
2401   }
2402
2403   return SDValue();
2404 }
2405
2406 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2407   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2408   if (Res.getNode()) return Res;
2409
2410   EVT VT = N->getValueType(0);
2411   SDLoc DL(N);
2412
2413   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2414   // plus a shift.
2415   if (VT.isSimple() && !VT.isVector()) {
2416     MVT Simple = VT.getSimpleVT();
2417     unsigned SimpleSize = Simple.getSizeInBits();
2418     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2419     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2420       SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2421       SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2422       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2423       // Compute the high part as N1.
2424       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2425             DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2426       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2427       // Compute the low part as N0.
2428       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2429       return CombineTo(N, Lo, Hi);
2430     }
2431   }
2432
2433   return SDValue();
2434 }
2435
2436 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2437   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2438   if (Res.getNode()) return Res;
2439
2440   EVT VT = N->getValueType(0);
2441   SDLoc DL(N);
2442
2443   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2444   // plus a shift.
2445   if (VT.isSimple() && !VT.isVector()) {
2446     MVT Simple = VT.getSimpleVT();
2447     unsigned SimpleSize = Simple.getSizeInBits();
2448     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2449     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2450       SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2451       SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2452       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2453       // Compute the high part as N1.
2454       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2455             DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2456       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2457       // Compute the low part as N0.
2458       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2459       return CombineTo(N, Lo, Hi);
2460     }
2461   }
2462
2463   return SDValue();
2464 }
2465
2466 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2467   // (smulo x, 2) -> (saddo x, x)
2468   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2469     if (C2->getAPIntValue() == 2)
2470       return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2471                          N->getOperand(0), N->getOperand(0));
2472
2473   return SDValue();
2474 }
2475
2476 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2477   // (umulo x, 2) -> (uaddo x, x)
2478   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2479     if (C2->getAPIntValue() == 2)
2480       return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2481                          N->getOperand(0), N->getOperand(0));
2482
2483   return SDValue();
2484 }
2485
2486 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2487   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2488   if (Res.getNode()) return Res;
2489
2490   return SDValue();
2491 }
2492
2493 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2494   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2495   if (Res.getNode()) return Res;
2496
2497   return SDValue();
2498 }
2499
2500 /// If this is a binary operator with two operands of the same opcode, try to
2501 /// simplify it.
2502 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2503   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2504   EVT VT = N0.getValueType();
2505   assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2506
2507   // Bail early if none of these transforms apply.
2508   if (N0.getNode()->getNumOperands() == 0) return SDValue();
2509
2510   // For each of OP in AND/OR/XOR:
2511   // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2512   // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2513   // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2514   // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2515   //
2516   // do not sink logical op inside of a vector extend, since it may combine
2517   // into a vsetcc.
2518   EVT Op0VT = N0.getOperand(0).getValueType();
2519   if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2520        N0.getOpcode() == ISD::SIGN_EXTEND ||
2521        // Avoid infinite looping with PromoteIntBinOp.
2522        (N0.getOpcode() == ISD::ANY_EXTEND &&
2523         (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2524        (N0.getOpcode() == ISD::TRUNCATE &&
2525         (!TLI.isZExtFree(VT, Op0VT) ||
2526          !TLI.isTruncateFree(Op0VT, VT)) &&
2527         TLI.isTypeLegal(Op0VT))) &&
2528       !VT.isVector() &&
2529       Op0VT == N1.getOperand(0).getValueType() &&
2530       (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2531     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2532                                  N0.getOperand(0).getValueType(),
2533                                  N0.getOperand(0), N1.getOperand(0));
2534     AddToWorklist(ORNode.getNode());
2535     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2536   }
2537
2538   // For each of OP in SHL/SRL/SRA/AND...
2539   //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2540   //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
2541   //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2542   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2543        N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2544       N0.getOperand(1) == N1.getOperand(1)) {
2545     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2546                                  N0.getOperand(0).getValueType(),
2547                                  N0.getOperand(0), N1.getOperand(0));
2548     AddToWorklist(ORNode.getNode());
2549     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2550                        ORNode, N0.getOperand(1));
2551   }
2552
2553   // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2554   // Only perform this optimization after type legalization and before
2555   // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2556   // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2557   // we don't want to undo this promotion.
2558   // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2559   // on scalars.
2560   if ((N0.getOpcode() == ISD::BITCAST ||
2561        N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2562       Level == AfterLegalizeTypes) {
2563     SDValue In0 = N0.getOperand(0);
2564     SDValue In1 = N1.getOperand(0);
2565     EVT In0Ty = In0.getValueType();
2566     EVT In1Ty = In1.getValueType();
2567     SDLoc DL(N);
2568     // If both incoming values are integers, and the original types are the
2569     // same.
2570     if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2571       SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2572       SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2573       AddToWorklist(Op.getNode());
2574       return BC;
2575     }
2576   }
2577
2578   // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2579   // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2580   // If both shuffles use the same mask, and both shuffle within a single
2581   // vector, then it is worthwhile to move the swizzle after the operation.
2582   // The type-legalizer generates this pattern when loading illegal
2583   // vector types from memory. In many cases this allows additional shuffle
2584   // optimizations.
2585   // There are other cases where moving the shuffle after the xor/and/or
2586   // is profitable even if shuffles don't perform a swizzle.
2587   // If both shuffles use the same mask, and both shuffles have the same first
2588   // or second operand, then it might still be profitable to move the shuffle
2589   // after the xor/and/or operation.
2590   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2591     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2592     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2593
2594     assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2595            "Inputs to shuffles are not the same type");
2596
2597     // Check that both shuffles use the same mask. The masks are known to be of
2598     // the same length because the result vector type is the same.
2599     // Check also that shuffles have only one use to avoid introducing extra
2600     // instructions.
2601     if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2602         SVN0->getMask().equals(SVN1->getMask())) {
2603       SDValue ShOp = N0->getOperand(1);
2604
2605       // Don't try to fold this node if it requires introducing a
2606       // build vector of all zeros that might be illegal at this stage.
2607       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2608         if (!LegalTypes)
2609           ShOp = DAG.getConstant(0, VT);
2610         else
2611           ShOp = SDValue();
2612       }
2613
2614       // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2615       // (OR  (shuf (A, C), shuf (B, C)) -> shuf (OR  (A, B), C)
2616       // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2617       if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2618         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2619                                       N0->getOperand(0), N1->getOperand(0));
2620         AddToWorklist(NewNode.getNode());
2621         return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2622                                     &SVN0->getMask()[0]);
2623       }
2624
2625       // Don't try to fold this node if it requires introducing a
2626       // build vector of all zeros that might be illegal at this stage.
2627       ShOp = N0->getOperand(0);
2628       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2629         if (!LegalTypes)
2630           ShOp = DAG.getConstant(0, VT);
2631         else
2632           ShOp = SDValue();
2633       }
2634
2635       // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2636       // (OR  (shuf (C, A), shuf (C, B)) -> shuf (C, OR  (A, B))
2637       // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2638       if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2639         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2640                                       N0->getOperand(1), N1->getOperand(1));
2641         AddToWorklist(NewNode.getNode());
2642         return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2643                                     &SVN0->getMask()[0]);
2644       }
2645     }
2646   }
2647
2648   return SDValue();
2649 }
2650
2651 SDValue DAGCombiner::visitAND(SDNode *N) {
2652   SDValue N0 = N->getOperand(0);
2653   SDValue N1 = N->getOperand(1);
2654   SDValue LL, LR, RL, RR, CC0, CC1;
2655   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2656   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2657   EVT VT = N1.getValueType();
2658   unsigned BitWidth = VT.getScalarType().getSizeInBits();
2659
2660   // fold vector ops
2661   if (VT.isVector()) {
2662     SDValue FoldedVOp = SimplifyVBinOp(N);
2663     if (FoldedVOp.getNode()) return FoldedVOp;
2664
2665     // fold (and x, 0) -> 0, vector edition
2666     if (ISD::isBuildVectorAllZeros(N0.getNode()))
2667       // do not return N0, because undef node may exist in N0
2668       return DAG.getConstant(
2669           APInt::getNullValue(
2670               N0.getValueType().getScalarType().getSizeInBits()),
2671           N0.getValueType());
2672     if (ISD::isBuildVectorAllZeros(N1.getNode()))
2673       // do not return N1, because undef node may exist in N1
2674       return DAG.getConstant(
2675           APInt::getNullValue(
2676               N1.getValueType().getScalarType().getSizeInBits()),
2677           N1.getValueType());
2678
2679     // fold (and x, -1) -> x, vector edition
2680     if (ISD::isBuildVectorAllOnes(N0.getNode()))
2681       return N1;
2682     if (ISD::isBuildVectorAllOnes(N1.getNode()))
2683       return N0;
2684   }
2685
2686   // fold (and x, undef) -> 0
2687   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2688     return DAG.getConstant(0, VT);
2689   // fold (and c1, c2) -> c1&c2
2690   if (N0C && N1C)
2691     return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
2692   // canonicalize constant to RHS
2693   if (N0C && !N1C)
2694     return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2695   // fold (and x, -1) -> x
2696   if (N1C && N1C->isAllOnesValue())
2697     return N0;
2698   // if (and x, c) is known to be zero, return 0
2699   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2700                                    APInt::getAllOnesValue(BitWidth)))
2701     return DAG.getConstant(0, VT);
2702   // reassociate and
2703   SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1);
2704   if (RAND.getNode())
2705     return RAND;
2706   // fold (and (or x, C), D) -> D if (C & D) == D
2707   if (N1C && N0.getOpcode() == ISD::OR)
2708     if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2709       if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2710         return N1;
2711   // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2712   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2713     SDValue N0Op0 = N0.getOperand(0);
2714     APInt Mask = ~N1C->getAPIntValue();
2715     Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2716     if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2717       SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2718                                  N0.getValueType(), N0Op0);
2719
2720       // Replace uses of the AND with uses of the Zero extend node.
2721       CombineTo(N, Zext);
2722
2723       // We actually want to replace all uses of the any_extend with the
2724       // zero_extend, to avoid duplicating things.  This will later cause this
2725       // AND to be folded.
2726       CombineTo(N0.getNode(), Zext);
2727       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2728     }
2729   }
2730   // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2731   // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2732   // already be zero by virtue of the width of the base type of the load.
2733   //
2734   // the 'X' node here can either be nothing or an extract_vector_elt to catch
2735   // more cases.
2736   if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2737        N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2738       N0.getOpcode() == ISD::LOAD) {
2739     LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2740                                          N0 : N0.getOperand(0) );
2741
2742     // Get the constant (if applicable) the zero'th operand is being ANDed with.
2743     // This can be a pure constant or a vector splat, in which case we treat the
2744     // vector as a scalar and use the splat value.
2745     APInt Constant = APInt::getNullValue(1);
2746     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2747       Constant = C->getAPIntValue();
2748     } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2749       APInt SplatValue, SplatUndef;
2750       unsigned SplatBitSize;
2751       bool HasAnyUndefs;
2752       bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2753                                              SplatBitSize, HasAnyUndefs);
2754       if (IsSplat) {
2755         // Undef bits can contribute to a possible optimisation if set, so
2756         // set them.
2757         SplatValue |= SplatUndef;
2758
2759         // The splat value may be something like "0x00FFFFFF", which means 0 for
2760         // the first vector value and FF for the rest, repeating. We need a mask
2761         // that will apply equally to all members of the vector, so AND all the
2762         // lanes of the constant together.
2763         EVT VT = Vector->getValueType(0);
2764         unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2765
2766         // If the splat value has been compressed to a bitlength lower
2767         // than the size of the vector lane, we need to re-expand it to
2768         // the lane size.
2769         if (BitWidth > SplatBitSize)
2770           for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2771                SplatBitSize < BitWidth;
2772                SplatBitSize = SplatBitSize * 2)
2773             SplatValue |= SplatValue.shl(SplatBitSize);
2774
2775         Constant = APInt::getAllOnesValue(BitWidth);
2776         for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2777           Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2778       }
2779     }
2780
2781     // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2782     // actually legal and isn't going to get expanded, else this is a false
2783     // optimisation.
2784     bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2785                                                     Load->getMemoryVT());
2786
2787     // Resize the constant to the same size as the original memory access before
2788     // extension. If it is still the AllOnesValue then this AND is completely
2789     // unneeded.
2790     Constant =
2791       Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2792
2793     bool B;
2794     switch (Load->getExtensionType()) {
2795     default: B = false; break;
2796     case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2797     case ISD::ZEXTLOAD:
2798     case ISD::NON_EXTLOAD: B = true; break;
2799     }
2800
2801     if (B && Constant.isAllOnesValue()) {
2802       // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2803       // preserve semantics once we get rid of the AND.
2804       SDValue NewLoad(Load, 0);
2805       if (Load->getExtensionType() == ISD::EXTLOAD) {
2806         NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
2807                               Load->getValueType(0), SDLoc(Load),
2808                               Load->getChain(), Load->getBasePtr(),
2809                               Load->getOffset(), Load->getMemoryVT(),
2810                               Load->getMemOperand());
2811         // Replace uses of the EXTLOAD with the new ZEXTLOAD.
2812         if (Load->getNumValues() == 3) {
2813           // PRE/POST_INC loads have 3 values.
2814           SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2815                            NewLoad.getValue(2) };
2816           CombineTo(Load, To, 3, true);
2817         } else {
2818           CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2819         }
2820       }
2821
2822       // Fold the AND away, taking care not to fold to the old load node if we
2823       // replaced it.
2824       CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2825
2826       return SDValue(N, 0); // Return N so it doesn't get rechecked!
2827     }
2828   }
2829   // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2830   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2831     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2832     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2833
2834     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2835         LL.getValueType().isInteger()) {
2836       // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2837       if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2838         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2839                                      LR.getValueType(), LL, RL);
2840         AddToWorklist(ORNode.getNode());
2841         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2842       }
2843       // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2844       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2845         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2846                                       LR.getValueType(), LL, RL);
2847         AddToWorklist(ANDNode.getNode());
2848         return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
2849       }
2850       // fold (and (setgt X,  -1), (setgt Y,  -1)) -> (setgt (or X, Y), -1)
2851       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2852         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2853                                      LR.getValueType(), LL, RL);
2854         AddToWorklist(ORNode.getNode());
2855         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2856       }
2857     }
2858     // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2859     if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2860         Op0 == Op1 && LL.getValueType().isInteger() &&
2861       Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2862                                  cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2863                                 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2864                                  cast<ConstantSDNode>(RR)->isNullValue()))) {
2865       SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(),
2866                                     LL, DAG.getConstant(1, LL.getValueType()));
2867       AddToWorklist(ADDNode.getNode());
2868       return DAG.getSetCC(SDLoc(N), VT, ADDNode,
2869                           DAG.getConstant(2, LL.getValueType()), ISD::SETUGE);
2870     }
2871     // canonicalize equivalent to ll == rl
2872     if (LL == RR && LR == RL) {
2873       Op1 = ISD::getSetCCSwappedOperands(Op1);
2874       std::swap(RL, RR);
2875     }
2876     if (LL == RL && LR == RR) {
2877       bool isInteger = LL.getValueType().isInteger();
2878       ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2879       if (Result != ISD::SETCC_INVALID &&
2880           (!LegalOperations ||
2881            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2882             TLI.isOperationLegal(ISD::SETCC,
2883                             getSetCCResultType(N0.getSimpleValueType())))))
2884         return DAG.getSetCC(SDLoc(N), N0.getValueType(),
2885                             LL, LR, Result);
2886     }
2887   }
2888
2889   // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
2890   if (N0.getOpcode() == N1.getOpcode()) {
2891     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2892     if (Tmp.getNode()) return Tmp;
2893   }
2894
2895   // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2896   // fold (and (sra)) -> (and (srl)) when possible.
2897   if (!VT.isVector() &&
2898       SimplifyDemandedBits(SDValue(N, 0)))
2899     return SDValue(N, 0);
2900
2901   // fold (zext_inreg (extload x)) -> (zextload x)
2902   if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
2903     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2904     EVT MemVT = LN0->getMemoryVT();
2905     // If we zero all the possible extended bits, then we can turn this into
2906     // a zextload if we are running before legalize or the operation is legal.
2907     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2908     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2909                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2910         ((!LegalOperations && !LN0->isVolatile()) ||
2911          TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2912       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2913                                        LN0->getChain(), LN0->getBasePtr(),
2914                                        MemVT, LN0->getMemOperand());
2915       AddToWorklist(N);
2916       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2917       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2918     }
2919   }
2920   // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
2921   if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
2922       N0.hasOneUse()) {
2923     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2924     EVT MemVT = LN0->getMemoryVT();
2925     // If we zero all the possible extended bits, then we can turn this into
2926     // a zextload if we are running before legalize or the operation is legal.
2927     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2928     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2929                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2930         ((!LegalOperations && !LN0->isVolatile()) ||
2931          TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2932       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2933                                        LN0->getChain(), LN0->getBasePtr(),
2934                                        MemVT, LN0->getMemOperand());
2935       AddToWorklist(N);
2936       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2937       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2938     }
2939   }
2940
2941   // fold (and (load x), 255) -> (zextload x, i8)
2942   // fold (and (extload x, i16), 255) -> (zextload x, i8)
2943   // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2944   if (N1C && (N0.getOpcode() == ISD::LOAD ||
2945               (N0.getOpcode() == ISD::ANY_EXTEND &&
2946                N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2947     bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2948     LoadSDNode *LN0 = HasAnyExt
2949       ? cast<LoadSDNode>(N0.getOperand(0))
2950       : cast<LoadSDNode>(N0);
2951     if (LN0->getExtensionType() != ISD::SEXTLOAD &&
2952         LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
2953       uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
2954       if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2955         EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2956         EVT LoadedVT = LN0->getMemoryVT();
2957
2958         if (ExtVT == LoadedVT &&
2959             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2960           EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2961
2962           SDValue NewLoad =
2963             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2964                            LN0->getChain(), LN0->getBasePtr(), ExtVT,
2965                            LN0->getMemOperand());
2966           AddToWorklist(N);
2967           CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2968           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2969         }
2970
2971         // Do not change the width of a volatile load.
2972         // Do not generate loads of non-round integer types since these can
2973         // be expensive (and would be wrong if the type is not byte sized).
2974         if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2975             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2976           EVT PtrType = LN0->getOperand(1).getValueType();
2977
2978           unsigned Alignment = LN0->getAlignment();
2979           SDValue NewPtr = LN0->getBasePtr();
2980
2981           // For big endian targets, we need to add an offset to the pointer
2982           // to load the correct bytes.  For little endian systems, we merely
2983           // need to read fewer bytes from the same pointer.
2984           if (TLI.isBigEndian()) {
2985             unsigned LVTStoreBytes = LoadedVT.getStoreSize();
2986             unsigned EVTStoreBytes = ExtVT.getStoreSize();
2987             unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
2988             NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
2989                                  NewPtr, DAG.getConstant(PtrOff, PtrType));
2990             Alignment = MinAlign(Alignment, PtrOff);
2991           }
2992
2993           AddToWorklist(NewPtr.getNode());
2994
2995           EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2996           SDValue Load =
2997             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2998                            LN0->getChain(), NewPtr,
2999                            LN0->getPointerInfo(),
3000                            ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
3001                            LN0->isInvariant(), Alignment, LN0->getAAInfo());
3002           AddToWorklist(N);
3003           CombineTo(LN0, Load, Load.getValue(1));
3004           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3005         }
3006       }
3007     }
3008   }
3009
3010   if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
3011       VT.getSizeInBits() <= 64) {
3012     if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3013       APInt ADDC = ADDI->getAPIntValue();
3014       if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3015         // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
3016         // immediate for an add, but it is legal if its top c2 bits are set,
3017         // transform the ADD so the immediate doesn't need to be materialized
3018         // in a register.
3019         if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
3020           APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
3021                                              SRLI->getZExtValue());
3022           if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
3023             ADDC |= Mask;
3024             if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3025               SDValue NewAdd =
3026                 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
3027                             N0.getOperand(0), DAG.getConstant(ADDC, VT));
3028               CombineTo(N0.getNode(), NewAdd);
3029               return SDValue(N, 0); // Return N so it doesn't get rechecked!
3030             }
3031           }
3032         }
3033       }
3034     }
3035   }
3036
3037   // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3038   if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3039     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3040                                        N0.getOperand(1), false);
3041     if (BSwap.getNode())
3042       return BSwap;
3043   }
3044
3045   return SDValue();
3046 }
3047
3048 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
3049 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3050                                         bool DemandHighBits) {
3051   if (!LegalOperations)
3052     return SDValue();
3053
3054   EVT VT = N->getValueType(0);
3055   if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3056     return SDValue();
3057   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3058     return SDValue();
3059
3060   // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3061   bool LookPassAnd0 = false;
3062   bool LookPassAnd1 = false;
3063   if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3064       std::swap(N0, N1);
3065   if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3066       std::swap(N0, N1);
3067   if (N0.getOpcode() == ISD::AND) {
3068     if (!N0.getNode()->hasOneUse())
3069       return SDValue();
3070     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3071     if (!N01C || N01C->getZExtValue() != 0xFF00)
3072       return SDValue();
3073     N0 = N0.getOperand(0);
3074     LookPassAnd0 = true;
3075   }
3076
3077   if (N1.getOpcode() == ISD::AND) {
3078     if (!N1.getNode()->hasOneUse())
3079       return SDValue();
3080     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3081     if (!N11C || N11C->getZExtValue() != 0xFF)
3082       return SDValue();
3083     N1 = N1.getOperand(0);
3084     LookPassAnd1 = true;
3085   }
3086
3087   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3088     std::swap(N0, N1);
3089   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3090     return SDValue();
3091   if (!N0.getNode()->hasOneUse() ||
3092       !N1.getNode()->hasOneUse())
3093     return SDValue();
3094
3095   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3096   ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3097   if (!N01C || !N11C)
3098     return SDValue();
3099   if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3100     return SDValue();
3101
3102   // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3103   SDValue N00 = N0->getOperand(0);
3104   if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3105     if (!N00.getNode()->hasOneUse())
3106       return SDValue();
3107     ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3108     if (!N001C || N001C->getZExtValue() != 0xFF)
3109       return SDValue();
3110     N00 = N00.getOperand(0);
3111     LookPassAnd0 = true;
3112   }
3113
3114   SDValue N10 = N1->getOperand(0);
3115   if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3116     if (!N10.getNode()->hasOneUse())
3117       return SDValue();
3118     ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3119     if (!N101C || N101C->getZExtValue() != 0xFF00)
3120       return SDValue();
3121     N10 = N10.getOperand(0);
3122     LookPassAnd1 = true;
3123   }
3124
3125   if (N00 != N10)
3126     return SDValue();
3127
3128   // Make sure everything beyond the low halfword gets set to zero since the SRL
3129   // 16 will clear the top bits.
3130   unsigned OpSizeInBits = VT.getSizeInBits();
3131   if (DemandHighBits && OpSizeInBits > 16) {
3132     // If the left-shift isn't masked out then the only way this is a bswap is
3133     // if all bits beyond the low 8 are 0. In that case the entire pattern
3134     // reduces to a left shift anyway: leave it for other parts of the combiner.
3135     if (!LookPassAnd0)
3136       return SDValue();
3137
3138     // However, if the right shift isn't masked out then it might be because
3139     // it's not needed. See if we can spot that too.
3140     if (!LookPassAnd1 &&
3141         !DAG.MaskedValueIsZero(
3142             N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3143       return SDValue();
3144   }
3145
3146   SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3147   if (OpSizeInBits > 16)
3148     Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
3149                       DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
3150   return Res;
3151 }
3152
3153 /// Return true if the specified node is an element that makes up a 32-bit
3154 /// packed halfword byteswap.
3155 /// ((x & 0x000000ff) << 8) |
3156 /// ((x & 0x0000ff00) >> 8) |
3157 /// ((x & 0x00ff0000) << 8) |
3158 /// ((x & 0xff000000) >> 8)
3159 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
3160   if (!N.getNode()->hasOneUse())
3161     return false;
3162
3163   unsigned Opc = N.getOpcode();
3164   if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3165     return false;
3166
3167   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3168   if (!N1C)
3169     return false;
3170
3171   unsigned Num;
3172   switch (N1C->getZExtValue()) {
3173   default:
3174     return false;
3175   case 0xFF:       Num = 0; break;
3176   case 0xFF00:     Num = 1; break;
3177   case 0xFF0000:   Num = 2; break;
3178   case 0xFF000000: Num = 3; break;
3179   }
3180
3181   // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3182   SDValue N0 = N.getOperand(0);
3183   if (Opc == ISD::AND) {
3184     if (Num == 0 || Num == 2) {
3185       // (x >> 8) & 0xff
3186       // (x >> 8) & 0xff0000
3187       if (N0.getOpcode() != ISD::SRL)
3188         return false;
3189       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3190       if (!C || C->getZExtValue() != 8)
3191         return false;
3192     } else {
3193       // (x << 8) & 0xff00
3194       // (x << 8) & 0xff000000
3195       if (N0.getOpcode() != ISD::SHL)
3196         return false;
3197       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3198       if (!C || C->getZExtValue() != 8)
3199         return false;
3200     }
3201   } else if (Opc == ISD::SHL) {
3202     // (x & 0xff) << 8
3203     // (x & 0xff0000) << 8
3204     if (Num != 0 && Num != 2)
3205       return false;
3206     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3207     if (!C || C->getZExtValue() != 8)
3208       return false;
3209   } else { // Opc == ISD::SRL
3210     // (x & 0xff00) >> 8
3211     // (x & 0xff000000) >> 8
3212     if (Num != 1 && Num != 3)
3213       return false;
3214     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3215     if (!C || C->getZExtValue() != 8)
3216       return false;
3217   }
3218
3219   if (Parts[Num])
3220     return false;
3221
3222   Parts[Num] = N0.getOperand(0).getNode();
3223   return true;
3224 }
3225
3226 /// Match a 32-bit packed halfword bswap. That is
3227 /// ((x & 0x000000ff) << 8) |
3228 /// ((x & 0x0000ff00) >> 8) |
3229 /// ((x & 0x00ff0000) << 8) |
3230 /// ((x & 0xff000000) >> 8)
3231 /// => (rotl (bswap x), 16)
3232 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3233   if (!LegalOperations)
3234     return SDValue();
3235
3236   EVT VT = N->getValueType(0);
3237   if (VT != MVT::i32)
3238     return SDValue();
3239   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3240     return SDValue();
3241
3242   // Look for either
3243   // (or (or (and), (and)), (or (and), (and)))
3244   // (or (or (or (and), (and)), (and)), (and))
3245   if (N0.getOpcode() != ISD::OR)
3246     return SDValue();
3247   SDValue N00 = N0.getOperand(0);
3248   SDValue N01 = N0.getOperand(1);
3249   SDNode *Parts[4] = {};
3250
3251   if (N1.getOpcode() == ISD::OR &&
3252       N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3253     // (or (or (and), (and)), (or (and), (and)))
3254     SDValue N000 = N00.getOperand(0);
3255     if (!isBSwapHWordElement(N000, Parts))
3256       return SDValue();
3257
3258     SDValue N001 = N00.getOperand(1);
3259     if (!isBSwapHWordElement(N001, Parts))
3260       return SDValue();
3261     SDValue N010 = N01.getOperand(0);
3262     if (!isBSwapHWordElement(N010, Parts))
3263       return SDValue();
3264     SDValue N011 = N01.getOperand(1);
3265     if (!isBSwapHWordElement(N011, Parts))
3266       return SDValue();
3267   } else {
3268     // (or (or (or (and), (and)), (and)), (and))
3269     if (!isBSwapHWordElement(N1, Parts))
3270       return SDValue();
3271     if (!isBSwapHWordElement(N01, Parts))
3272       return SDValue();
3273     if (N00.getOpcode() != ISD::OR)
3274       return SDValue();
3275     SDValue N000 = N00.getOperand(0);
3276     if (!isBSwapHWordElement(N000, Parts))
3277       return SDValue();
3278     SDValue N001 = N00.getOperand(1);
3279     if (!isBSwapHWordElement(N001, Parts))
3280       return SDValue();
3281   }
3282
3283   // Make sure the parts are all coming from the same node.
3284   if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3285     return SDValue();
3286
3287   SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
3288                               SDValue(Parts[0],0));
3289
3290   // Result of the bswap should be rotated by 16. If it's not legal, then
3291   // do  (x << 16) | (x >> 16).
3292   SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3293   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3294     return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
3295   if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3296     return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3297   return DAG.getNode(ISD::OR, SDLoc(N), VT,
3298                      DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3299                      DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
3300 }
3301
3302 SDValue DAGCombiner::visitOR(SDNode *N) {
3303   SDValue N0 = N->getOperand(0);
3304   SDValue N1 = N->getOperand(1);
3305   SDValue LL, LR, RL, RR, CC0, CC1;
3306   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3307   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3308   EVT VT = N1.getValueType();
3309
3310   // fold vector ops
3311   if (VT.isVector()) {
3312     SDValue FoldedVOp = SimplifyVBinOp(N);
3313     if (FoldedVOp.getNode()) return FoldedVOp;
3314
3315     // fold (or x, 0) -> x, vector edition
3316     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3317       return N1;
3318     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3319       return N0;
3320
3321     // fold (or x, -1) -> -1, vector edition
3322     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3323       // do not return N0, because undef node may exist in N0
3324       return DAG.getConstant(
3325           APInt::getAllOnesValue(
3326               N0.getValueType().getScalarType().getSizeInBits()),
3327           N0.getValueType());
3328     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3329       // do not return N1, because undef node may exist in N1
3330       return DAG.getConstant(
3331           APInt::getAllOnesValue(
3332               N1.getValueType().getScalarType().getSizeInBits()),
3333           N1.getValueType());
3334
3335     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3336     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3337     // Do this only if the resulting shuffle is legal.
3338     if (isa<ShuffleVectorSDNode>(N0) &&
3339         isa<ShuffleVectorSDNode>(N1) &&
3340         // Avoid folding a node with illegal type.
3341         TLI.isTypeLegal(VT) &&
3342         N0->getOperand(1) == N1->getOperand(1) &&
3343         ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3344       bool CanFold = true;
3345       unsigned NumElts = VT.getVectorNumElements();
3346       const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3347       const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3348       // We construct two shuffle masks:
3349       // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3350       // and N1 as the second operand.
3351       // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3352       // and N0 as the second operand.
3353       // We do this because OR is commutable and therefore there might be
3354       // two ways to fold this node into a shuffle.
3355       SmallVector<int,4> Mask1;
3356       SmallVector<int,4> Mask2;
3357
3358       for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3359         int M0 = SV0->getMaskElt(i);
3360         int M1 = SV1->getMaskElt(i);
3361
3362         // Both shuffle indexes are undef. Propagate Undef.
3363         if (M0 < 0 && M1 < 0) {
3364           Mask1.push_back(M0);
3365           Mask2.push_back(M0);
3366           continue;
3367         }
3368
3369         if (M0 < 0 || M1 < 0 ||
3370             (M0 < (int)NumElts && M1 < (int)NumElts) ||
3371             (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3372           CanFold = false;
3373           break;
3374         }
3375
3376         Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3377         Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3378       }
3379
3380       if (CanFold) {
3381         // Fold this sequence only if the resulting shuffle is 'legal'.
3382         if (TLI.isShuffleMaskLegal(Mask1, VT))
3383           return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3384                                       N1->getOperand(0), &Mask1[0]);
3385         if (TLI.isShuffleMaskLegal(Mask2, VT))
3386           return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3387                                       N0->getOperand(0), &Mask2[0]);
3388       }
3389     }
3390   }
3391
3392   // fold (or x, undef) -> -1
3393   if (!LegalOperations &&
3394       (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3395     EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3396     return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3397   }
3398   // fold (or c1, c2) -> c1|c2
3399   if (N0C && N1C)
3400     return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
3401   // canonicalize constant to RHS
3402   if (N0C && !N1C)
3403     return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3404   // fold (or x, 0) -> x
3405   if (N1C && N1C->isNullValue())
3406     return N0;
3407   // fold (or x, -1) -> -1
3408   if (N1C && N1C->isAllOnesValue())
3409     return N1;
3410   // fold (or x, c) -> c iff (x & ~c) == 0
3411   if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3412     return N1;
3413
3414   // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3415   SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3416   if (BSwap.getNode())
3417     return BSwap;
3418   BSwap = MatchBSwapHWordLow(N, N0, N1);
3419   if (BSwap.getNode())
3420     return BSwap;
3421
3422   // reassociate or
3423   SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1);
3424   if (ROR.getNode())
3425     return ROR;
3426   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3427   // iff (c1 & c2) == 0.
3428   if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3429              isa<ConstantSDNode>(N0.getOperand(1))) {
3430     ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3431     if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3432       SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1);
3433       if (!COR.getNode())
3434         return SDValue();
3435       return DAG.getNode(ISD::AND, SDLoc(N), VT,
3436                          DAG.getNode(ISD::OR, SDLoc(N0), VT,
3437                                      N0.getOperand(0), N1), COR);
3438     }
3439   }
3440   // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3441   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3442     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3443     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3444
3445     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3446         LL.getValueType().isInteger()) {
3447       // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3448       // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3449       if (cast<ConstantSDNode>(LR)->isNullValue() &&
3450           (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3451         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3452                                      LR.getValueType(), LL, RL);
3453         AddToWorklist(ORNode.getNode());
3454         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
3455       }
3456       // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3457       // fold (or (setgt X, -1), (setgt Y  -1)) -> (setgt (and X, Y), -1)
3458       if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3459           (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3460         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3461                                       LR.getValueType(), LL, RL);
3462         AddToWorklist(ANDNode.getNode());
3463         return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
3464       }
3465     }
3466     // canonicalize equivalent to ll == rl
3467     if (LL == RR && LR == RL) {
3468       Op1 = ISD::getSetCCSwappedOperands(Op1);
3469       std::swap(RL, RR);
3470     }
3471     if (LL == RL && LR == RR) {
3472       bool isInteger = LL.getValueType().isInteger();
3473       ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3474       if (Result != ISD::SETCC_INVALID &&
3475           (!LegalOperations ||
3476            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3477             TLI.isOperationLegal(ISD::SETCC,
3478               getSetCCResultType(N0.getValueType())))))
3479         return DAG.getSetCC(SDLoc(N), N0.getValueType(),
3480                             LL, LR, Result);
3481     }
3482   }
3483
3484   // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
3485   if (N0.getOpcode() == N1.getOpcode()) {
3486     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3487     if (Tmp.getNode()) return Tmp;
3488   }
3489
3490   // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
3491   if (N0.getOpcode() == ISD::AND &&
3492       N1.getOpcode() == ISD::AND &&
3493       N0.getOperand(1).getOpcode() == ISD::Constant &&
3494       N1.getOperand(1).getOpcode() == ISD::Constant &&
3495       // Don't increase # computations.
3496       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3497     // We can only do this xform if we know that bits from X that are set in C2
3498     // but not in C1 are already zero.  Likewise for Y.
3499     const APInt &LHSMask =
3500       cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3501     const APInt &RHSMask =
3502       cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3503
3504     if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3505         DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3506       SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3507                               N0.getOperand(0), N1.getOperand(0));
3508       return DAG.getNode(ISD::AND, SDLoc(N), VT, X,
3509                          DAG.getConstant(LHSMask | RHSMask, VT));
3510     }
3511   }
3512
3513   // See if this is some rotate idiom.
3514   if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3515     return SDValue(Rot, 0);
3516
3517   // Simplify the operands using demanded-bits information.
3518   if (!VT.isVector() &&
3519       SimplifyDemandedBits(SDValue(N, 0)))
3520     return SDValue(N, 0);
3521
3522   return SDValue();
3523 }
3524
3525 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
3526 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3527   if (Op.getOpcode() == ISD::AND) {
3528     if (isa<ConstantSDNode>(Op.getOperand(1))) {
3529       Mask = Op.getOperand(1);
3530       Op = Op.getOperand(0);
3531     } else {
3532       return false;
3533     }
3534   }
3535
3536   if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3537     Shift = Op;
3538     return true;
3539   }
3540
3541   return false;
3542 }
3543
3544 // Return true if we can prove that, whenever Neg and Pos are both in the
3545 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos).  This means that
3546 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3547 //
3548 //     (or (shift1 X, Neg), (shift2 X, Pos))
3549 //
3550 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3551 // in direction shift1 by Neg.  The range [0, OpSize) means that we only need
3552 // to consider shift amounts with defined behavior.
3553 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3554   // If OpSize is a power of 2 then:
3555   //
3556   //  (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3557   //  (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3558   //
3559   // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3560   // for the stronger condition:
3561   //
3562   //     Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1)    [A]
3563   //
3564   // for all Neg and Pos.  Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3565   // we can just replace Neg with Neg' for the rest of the function.
3566   //
3567   // In other cases we check for the even stronger condition:
3568   //
3569   //     Neg == OpSize - Pos                                    [B]
3570   //
3571   // for all Neg and Pos.  Note that the (or ...) then invokes undefined
3572   // behavior if Pos == 0 (and consequently Neg == OpSize).
3573   //
3574   // We could actually use [A] whenever OpSize is a power of 2, but the
3575   // only extra cases that it would match are those uninteresting ones
3576   // where Neg and Pos are never in range at the same time.  E.g. for
3577   // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3578   // as well as (sub 32, Pos), but:
3579   //
3580   //     (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3581   //
3582   // always invokes undefined behavior for 32-bit X.
3583   //
3584   // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3585   unsigned MaskLoBits = 0;
3586   if (Neg.getOpcode() == ISD::AND &&
3587       isPowerOf2_64(OpSize) &&
3588       Neg.getOperand(1).getOpcode() == ISD::Constant &&
3589       cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3590     Neg = Neg.getOperand(0);
3591     MaskLoBits = Log2_64(OpSize);
3592   }
3593
3594   // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3595   if (Neg.getOpcode() != ISD::SUB)
3596     return 0;
3597   ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3598   if (!NegC)
3599     return 0;
3600   SDValue NegOp1 = Neg.getOperand(1);
3601
3602   // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3603   // Pos'.  The truncation is redundant for the purpose of the equality.
3604   if (MaskLoBits &&
3605       Pos.getOpcode() == ISD::AND &&
3606       Pos.getOperand(1).getOpcode() == ISD::Constant &&
3607       cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3608     Pos = Pos.getOperand(0);
3609
3610   // The condition we need is now:
3611   //
3612   //     (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3613   //
3614   // If NegOp1 == Pos then we need:
3615   //
3616   //              OpSize & Mask == NegC & Mask
3617   //
3618   // (because "x & Mask" is a truncation and distributes through subtraction).
3619   APInt Width;
3620   if (Pos == NegOp1)
3621     Width = NegC->getAPIntValue();
3622   // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3623   // Then the condition we want to prove becomes:
3624   //
3625   //     (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3626   //
3627   // which, again because "x & Mask" is a truncation, becomes:
3628   //
3629   //                NegC & Mask == (OpSize - PosC) & Mask
3630   //              OpSize & Mask == (NegC + PosC) & Mask
3631   else if (Pos.getOpcode() == ISD::ADD &&
3632            Pos.getOperand(0) == NegOp1 &&
3633            Pos.getOperand(1).getOpcode() == ISD::Constant)
3634     Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3635              NegC->getAPIntValue());
3636   else
3637     return false;
3638
3639   // Now we just need to check that OpSize & Mask == Width & Mask.
3640   if (MaskLoBits)
3641     // Opsize & Mask is 0 since Mask is Opsize - 1.
3642     return Width.getLoBits(MaskLoBits) == 0;
3643   return Width == OpSize;
3644 }
3645
3646 // A subroutine of MatchRotate used once we have found an OR of two opposite
3647 // shifts of Shifted.  If Neg == <operand size> - Pos then the OR reduces
3648 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3649 // former being preferred if supported.  InnerPos and InnerNeg are Pos and
3650 // Neg with outer conversions stripped away.
3651 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3652                                        SDValue Neg, SDValue InnerPos,
3653                                        SDValue InnerNeg, unsigned PosOpcode,
3654                                        unsigned NegOpcode, SDLoc DL) {
3655   // fold (or (shl x, (*ext y)),
3656   //          (srl x, (*ext (sub 32, y)))) ->
3657   //   (rotl x, y) or (rotr x, (sub 32, y))
3658   //
3659   // fold (or (shl x, (*ext (sub 32, y))),
3660   //          (srl x, (*ext y))) ->
3661   //   (rotr x, y) or (rotl x, (sub 32, y))
3662   EVT VT = Shifted.getValueType();
3663   if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3664     bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3665     return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3666                        HasPos ? Pos : Neg).getNode();
3667   }
3668
3669   return nullptr;
3670 }
3671
3672 // MatchRotate - Handle an 'or' of two operands.  If this is one of the many
3673 // idioms for rotate, and if the target supports rotation instructions, generate
3674 // a rot[lr].
3675 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3676   // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
3677   EVT VT = LHS.getValueType();
3678   if (!TLI.isTypeLegal(VT)) return nullptr;
3679
3680   // The target must have at least one rotate flavor.
3681   bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3682   bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3683   if (!HasROTL && !HasROTR) return nullptr;
3684
3685   // Match "(X shl/srl V1) & V2" where V2 may not be present.
3686   SDValue LHSShift;   // The shift.
3687   SDValue LHSMask;    // AND value if any.
3688   if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3689     return nullptr; // Not part of a rotate.
3690
3691   SDValue RHSShift;   // The shift.
3692   SDValue RHSMask;    // AND value if any.
3693   if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3694     return nullptr; // Not part of a rotate.
3695
3696   if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3697     return nullptr;   // Not shifting the same value.
3698
3699   if (LHSShift.getOpcode() == RHSShift.getOpcode())
3700     return nullptr;   // Shifts must disagree.
3701
3702   // Canonicalize shl to left side in a shl/srl pair.
3703   if (RHSShift.getOpcode() == ISD::SHL) {
3704     std::swap(LHS, RHS);
3705     std::swap(LHSShift, RHSShift);
3706     std::swap(LHSMask , RHSMask );
3707   }
3708
3709   unsigned OpSizeInBits = VT.getSizeInBits();
3710   SDValue LHSShiftArg = LHSShift.getOperand(0);
3711   SDValue LHSShiftAmt = LHSShift.getOperand(1);
3712   SDValue RHSShiftArg = RHSShift.getOperand(0);
3713   SDValue RHSShiftAmt = RHSShift.getOperand(1);
3714
3715   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3716   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3717   if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3718       RHSShiftAmt.getOpcode() == ISD::Constant) {
3719     uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3720     uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3721     if ((LShVal + RShVal) != OpSizeInBits)
3722       return nullptr;
3723
3724     SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3725                               LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3726
3727     // If there is an AND of either shifted operand, apply it to the result.
3728     if (LHSMask.getNode() || RHSMask.getNode()) {
3729       APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3730
3731       if (LHSMask.getNode()) {
3732         APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3733         Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3734       }
3735       if (RHSMask.getNode()) {
3736         APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3737         Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3738       }
3739
3740       Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
3741     }
3742
3743     return Rot.getNode();
3744   }
3745
3746   // If there is a mask here, and we have a variable shift, we can't be sure
3747   // that we're masking out the right stuff.
3748   if (LHSMask.getNode() || RHSMask.getNode())
3749     return nullptr;
3750
3751   // If the shift amount is sign/zext/any-extended just peel it off.
3752   SDValue LExtOp0 = LHSShiftAmt;
3753   SDValue RExtOp0 = RHSShiftAmt;
3754   if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3755        LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3756        LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3757        LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3758       (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3759        RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3760        RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3761        RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3762     LExtOp0 = LHSShiftAmt.getOperand(0);
3763     RExtOp0 = RHSShiftAmt.getOperand(0);
3764   }
3765
3766   SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3767                                    LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3768   if (TryL)
3769     return TryL;
3770
3771   SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3772                                    RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3773   if (TryR)
3774     return TryR;
3775
3776   return nullptr;
3777 }
3778
3779 SDValue DAGCombiner::visitXOR(SDNode *N) {
3780   SDValue N0 = N->getOperand(0);
3781   SDValue N1 = N->getOperand(1);
3782   SDValue LHS, RHS, CC;
3783   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3784   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3785   EVT VT = N0.getValueType();
3786
3787   // fold vector ops
3788   if (VT.isVector()) {
3789     SDValue FoldedVOp = SimplifyVBinOp(N);
3790     if (FoldedVOp.getNode()) return FoldedVOp;
3791
3792     // fold (xor x, 0) -> x, vector edition
3793     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3794       return N1;
3795     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3796       return N0;
3797   }
3798
3799   // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3800   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3801     return DAG.getConstant(0, VT);
3802   // fold (xor x, undef) -> undef
3803   if (N0.getOpcode() == ISD::UNDEF)
3804     return N0;
3805   if (N1.getOpcode() == ISD::UNDEF)
3806     return N1;
3807   // fold (xor c1, c2) -> c1^c2
3808   if (N0C && N1C)
3809     return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
3810   // canonicalize constant to RHS
3811   if (N0C && !N1C)
3812     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3813   // fold (xor x, 0) -> x
3814   if (N1C && N1C->isNullValue())
3815     return N0;
3816   // reassociate xor
3817   SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1);
3818   if (RXOR.getNode())
3819     return RXOR;
3820
3821   // fold !(x cc y) -> (x !cc y)
3822   if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3823     bool isInt = LHS.getValueType().isInteger();
3824     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3825                                                isInt);
3826
3827     if (!LegalOperations ||
3828         TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3829       switch (N0.getOpcode()) {
3830       default:
3831         llvm_unreachable("Unhandled SetCC Equivalent!");
3832       case ISD::SETCC:
3833         return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
3834       case ISD::SELECT_CC:
3835         return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
3836                                N0.getOperand(3), NotCC);
3837       }
3838     }
3839   }
3840
3841   // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3842   if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3843       N0.getNode()->hasOneUse() &&
3844       isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3845     SDValue V = N0.getOperand(0);
3846     V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
3847                     DAG.getConstant(1, V.getValueType()));
3848     AddToWorklist(V.getNode());
3849     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
3850   }
3851
3852   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3853   if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3854       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3855     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3856     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3857       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3858       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3859       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3860       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
3861       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3862     }
3863   }
3864   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
3865   if (N1C && N1C->isAllOnesValue() &&
3866       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3867     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3868     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3869       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3870       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3871       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3872       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
3873       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3874     }
3875   }
3876   // fold (xor (and x, y), y) -> (and (not x), y)
3877   if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3878       N0->getOperand(1) == N1) {
3879     SDValue X = N0->getOperand(0);
3880     SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
3881     AddToWorklist(NotX.getNode());
3882     return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
3883   }
3884   // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
3885   if (N1C && N0.getOpcode() == ISD::XOR) {
3886     ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3887     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3888     if (N00C)
3889       return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
3890                          DAG.getConstant(N1C->getAPIntValue() ^
3891                                          N00C->getAPIntValue(), VT));
3892     if (N01C)
3893       return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
3894                          DAG.getConstant(N1C->getAPIntValue() ^
3895                                          N01C->getAPIntValue(), VT));
3896   }
3897   // fold (xor x, x) -> 0
3898   if (N0 == N1)
3899     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
3900
3901   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
3902   if (N0.getOpcode() == N1.getOpcode()) {
3903     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3904     if (Tmp.getNode()) return Tmp;
3905   }
3906
3907   // Simplify the expression using non-local knowledge.
3908   if (!VT.isVector() &&
3909       SimplifyDemandedBits(SDValue(N, 0)))
3910     return SDValue(N, 0);
3911
3912   return SDValue();
3913 }
3914
3915 /// Handle transforms common to the three shifts, when the shift amount is a
3916 /// constant.
3917 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
3918   // We can't and shouldn't fold opaque constants.
3919   if (Amt->isOpaque())
3920     return SDValue();
3921
3922   SDNode *LHS = N->getOperand(0).getNode();
3923   if (!LHS->hasOneUse()) return SDValue();
3924
3925   // We want to pull some binops through shifts, so that we have (and (shift))
3926   // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
3927   // thing happens with address calculations, so it's important to canonicalize
3928   // it.
3929   bool HighBitSet = false;  // Can we transform this if the high bit is set?
3930
3931   switch (LHS->getOpcode()) {
3932   default: return SDValue();
3933   case ISD::OR:
3934   case ISD::XOR:
3935     HighBitSet = false; // We can only transform sra if the high bit is clear.
3936     break;
3937   case ISD::AND:
3938     HighBitSet = true;  // We can only transform sra if the high bit is set.
3939     break;
3940   case ISD::ADD:
3941     if (N->getOpcode() != ISD::SHL)
3942       return SDValue(); // only shl(add) not sr[al](add).
3943     HighBitSet = false; // We can only transform sra if the high bit is clear.
3944     break;
3945   }
3946
3947   // We require the RHS of the binop to be a constant and not opaque as well.
3948   ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
3949   if (!BinOpCst || BinOpCst->isOpaque()) return SDValue();
3950
3951   // FIXME: disable this unless the input to the binop is a shift by a constant.
3952   // If it is not a shift, it pessimizes some common cases like:
3953   //
3954   //    void foo(int *X, int i) { X[i & 1235] = 1; }
3955   //    int bar(int *X, int i) { return X[i & 255]; }
3956   SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
3957   if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
3958        BinOpLHSVal->getOpcode() != ISD::SRA &&
3959        BinOpLHSVal->getOpcode() != ISD::SRL) ||
3960       !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
3961     return SDValue();
3962
3963   EVT VT = N->getValueType(0);
3964
3965   // If this is a signed shift right, and the high bit is modified by the
3966   // logical operation, do not perform the transformation. The highBitSet
3967   // boolean indicates the value of the high bit of the constant which would
3968   // cause it to be modified for this operation.
3969   if (N->getOpcode() == ISD::SRA) {
3970     bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
3971     if (BinOpRHSSignSet != HighBitSet)
3972       return SDValue();
3973   }
3974
3975   if (!TLI.isDesirableToCommuteWithShift(LHS))
3976     return SDValue();
3977
3978   // Fold the constants, shifting the binop RHS by the shift amount.
3979   SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
3980                                N->getValueType(0),
3981                                LHS->getOperand(1), N->getOperand(1));
3982   assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
3983
3984   // Create the new shift.
3985   SDValue NewShift = DAG.getNode(N->getOpcode(),
3986                                  SDLoc(LHS->getOperand(0)),
3987                                  VT, LHS->getOperand(0), N->getOperand(1));
3988
3989   // Create the new binop.
3990   return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
3991 }
3992
3993 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
3994   assert(N->getOpcode() == ISD::TRUNCATE);
3995   assert(N->getOperand(0).getOpcode() == ISD::AND);
3996
3997   // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
3998   if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
3999     SDValue N01 = N->getOperand(0).getOperand(1);
4000
4001     if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
4002       EVT TruncVT = N->getValueType(0);
4003       SDValue N00 = N->getOperand(0).getOperand(0);
4004       APInt TruncC = N01C->getAPIntValue();
4005       TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
4006
4007       return DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
4008                          DAG.getNode(ISD::TRUNCATE, SDLoc(N), TruncVT, N00),
4009                          DAG.getConstant(TruncC, TruncVT));
4010     }
4011   }
4012
4013   return SDValue();
4014 }
4015
4016 SDValue DAGCombiner::visitRotate(SDNode *N) {
4017   // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
4018   if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
4019       N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
4020     SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
4021     if (NewOp1.getNode())
4022       return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
4023                          N->getOperand(0), NewOp1);
4024   }
4025   return SDValue();
4026 }
4027
4028 SDValue DAGCombiner::visitSHL(SDNode *N) {
4029   SDValue N0 = N->getOperand(0);
4030   SDValue N1 = N->getOperand(1);
4031   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4032   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4033   EVT VT = N0.getValueType();
4034   unsigned OpSizeInBits = VT.getScalarSizeInBits();
4035
4036   // fold vector ops
4037   if (VT.isVector()) {
4038     SDValue FoldedVOp = SimplifyVBinOp(N);
4039     if (FoldedVOp.getNode()) return FoldedVOp;
4040
4041     BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4042     // If setcc produces all-one true value then:
4043     // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
4044     if (N1CV && N1CV->isConstant()) {
4045       if (N0.getOpcode() == ISD::AND) {
4046         SDValue N00 = N0->getOperand(0);
4047         SDValue N01 = N0->getOperand(1);
4048         BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
4049
4050         if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4051             TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4052                 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4053           SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, VT, N01CV, N1CV);
4054           if (C.getNode())
4055             return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4056         }
4057       } else {
4058         N1C = isConstOrConstSplat(N1);
4059       }
4060     }
4061   }
4062
4063   // fold (shl c1, c2) -> c1<<c2
4064   if (N0C && N1C)
4065     return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
4066   // fold (shl 0, x) -> 0
4067   if (N0C && N0C->isNullValue())
4068     return N0;
4069   // fold (shl x, c >= size(x)) -> undef
4070   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4071     return DAG.getUNDEF(VT);
4072   // fold (shl x, 0) -> x
4073   if (N1C && N1C->isNullValue())
4074     return N0;
4075   // fold (shl undef, x) -> 0
4076   if (N0.getOpcode() == ISD::UNDEF)
4077     return DAG.getConstant(0, VT);
4078   // if (shl x, c) is known to be zero, return 0
4079   if (DAG.MaskedValueIsZero(SDValue(N, 0),
4080                             APInt::getAllOnesValue(OpSizeInBits)))
4081     return DAG.getConstant(0, VT);
4082   // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4083   if (N1.getOpcode() == ISD::TRUNCATE &&
4084       N1.getOperand(0).getOpcode() == ISD::AND) {
4085     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4086     if (NewOp1.getNode())
4087       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4088   }
4089
4090   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4091     return SDValue(N, 0);
4092
4093   // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4094   if (N1C && N0.getOpcode() == ISD::SHL) {
4095     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4096       uint64_t c1 = N0C1->getZExtValue();
4097       uint64_t c2 = N1C->getZExtValue();
4098       if (c1 + c2 >= OpSizeInBits)
4099         return DAG.getConstant(0, VT);
4100       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4101                          DAG.getConstant(c1 + c2, N1.getValueType()));
4102     }
4103   }
4104
4105   // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4106   // For this to be valid, the second form must not preserve any of the bits
4107   // that are shifted out by the inner shift in the first form.  This means
4108   // the outer shift size must be >= the number of bits added by the ext.
4109   // As a corollary, we don't care what kind of ext it is.
4110   if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4111               N0.getOpcode() == ISD::ANY_EXTEND ||
4112               N0.getOpcode() == ISD::SIGN_EXTEND) &&
4113       N0.getOperand(0).getOpcode() == ISD::SHL) {
4114     SDValue N0Op0 = N0.getOperand(0);
4115     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4116       uint64_t c1 = N0Op0C1->getZExtValue();
4117       uint64_t c2 = N1C->getZExtValue();
4118       EVT InnerShiftVT = N0Op0.getValueType();
4119       uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4120       if (c2 >= OpSizeInBits - InnerShiftSize) {
4121         if (c1 + c2 >= OpSizeInBits)
4122           return DAG.getConstant(0, VT);
4123         return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
4124                            DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
4125                                        N0Op0->getOperand(0)),
4126                            DAG.getConstant(c1 + c2, N1.getValueType()));
4127       }
4128     }
4129   }
4130
4131   // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4132   // Only fold this if the inner zext has no other uses to avoid increasing
4133   // the total number of instructions.
4134   if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4135       N0.getOperand(0).getOpcode() == ISD::SRL) {
4136     SDValue N0Op0 = N0.getOperand(0);
4137     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4138       uint64_t c1 = N0Op0C1->getZExtValue();
4139       if (c1 < VT.getScalarSizeInBits()) {
4140         uint64_t c2 = N1C->getZExtValue();
4141         if (c1 == c2) {
4142           SDValue NewOp0 = N0.getOperand(0);
4143           EVT CountVT = NewOp0.getOperand(1).getValueType();
4144           SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(),
4145                                        NewOp0, DAG.getConstant(c2, CountVT));
4146           AddToWorklist(NewSHL.getNode());
4147           return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4148         }
4149       }
4150     }
4151   }
4152
4153   // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4154   //                               (and (srl x, (sub c1, c2), MASK)
4155   // Only fold this if the inner shift has no other uses -- if it does, folding
4156   // this will increase the total number of instructions.
4157   if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4158     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4159       uint64_t c1 = N0C1->getZExtValue();
4160       if (c1 < OpSizeInBits) {
4161         uint64_t c2 = N1C->getZExtValue();
4162         APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4163         SDValue Shift;
4164         if (c2 > c1) {
4165           Mask = Mask.shl(c2 - c1);
4166           Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4167                               DAG.getConstant(c2 - c1, N1.getValueType()));
4168         } else {
4169           Mask = Mask.lshr(c1 - c2);
4170           Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4171                               DAG.getConstant(c1 - c2, N1.getValueType()));
4172         }
4173         return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
4174                            DAG.getConstant(Mask, VT));
4175       }
4176     }
4177   }
4178   // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4179   if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4180     unsigned BitSize = VT.getScalarSizeInBits();
4181     SDValue HiBitsMask =
4182       DAG.getConstant(APInt::getHighBitsSet(BitSize,
4183                                             BitSize - N1C->getZExtValue()), VT);
4184     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4185                        HiBitsMask);
4186   }
4187
4188   // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
4189   // Variant of version done on multiply, except mul by a power of 2 is turned
4190   // into a shift.
4191   APInt Val;
4192   if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
4193       (isa<ConstantSDNode>(N0.getOperand(1)) ||
4194        isConstantSplatVector(N0.getOperand(1).getNode(), Val))) {
4195     SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
4196     SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
4197     return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
4198   }
4199
4200   if (N1C) {
4201     SDValue NewSHL = visitShiftByConstant(N, N1C);
4202     if (NewSHL.getNode())
4203       return NewSHL;
4204   }
4205
4206   return SDValue();
4207 }
4208
4209 SDValue DAGCombiner::visitSRA(SDNode *N) {
4210   SDValue N0 = N->getOperand(0);
4211   SDValue N1 = N->getOperand(1);
4212   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4213   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4214   EVT VT = N0.getValueType();
4215   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4216
4217   // fold vector ops
4218   if (VT.isVector()) {
4219     SDValue FoldedVOp = SimplifyVBinOp(N);
4220     if (FoldedVOp.getNode()) return FoldedVOp;
4221
4222     N1C = isConstOrConstSplat(N1);
4223   }
4224
4225   // fold (sra c1, c2) -> (sra c1, c2)
4226   if (N0C && N1C)
4227     return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
4228   // fold (sra 0, x) -> 0
4229   if (N0C && N0C->isNullValue())
4230     return N0;
4231   // fold (sra -1, x) -> -1
4232   if (N0C && N0C->isAllOnesValue())
4233     return N0;
4234   // fold (sra x, (setge c, size(x))) -> undef
4235   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4236     return DAG.getUNDEF(VT);
4237   // fold (sra x, 0) -> x
4238   if (N1C && N1C->isNullValue())
4239     return N0;
4240   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4241   // sext_inreg.
4242   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4243     unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4244     EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4245     if (VT.isVector())
4246       ExtVT = EVT::getVectorVT(*DAG.getContext(),
4247                                ExtVT, VT.getVectorNumElements());
4248     if ((!LegalOperations ||
4249          TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4250       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4251                          N0.getOperand(0), DAG.getValueType(ExtVT));
4252   }
4253
4254   // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4255   if (N1C && N0.getOpcode() == ISD::SRA) {
4256     if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4257       unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4258       if (Sum >= OpSizeInBits)
4259         Sum = OpSizeInBits - 1;
4260       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
4261                          DAG.getConstant(Sum, N1.getValueType()));
4262     }
4263   }
4264
4265   // fold (sra (shl X, m), (sub result_size, n))
4266   // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4267   // result_size - n != m.
4268   // If truncate is free for the target sext(shl) is likely to result in better
4269   // code.
4270   if (N0.getOpcode() == ISD::SHL && N1C) {
4271     // Get the two constanst of the shifts, CN0 = m, CN = n.
4272     const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4273     if (N01C) {
4274       LLVMContext &Ctx = *DAG.getContext();
4275       // Determine what the truncate's result bitsize and type would be.
4276       EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4277
4278       if (VT.isVector())
4279         TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4280
4281       // Determine the residual right-shift amount.
4282       signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4283
4284       // If the shift is not a no-op (in which case this should be just a sign
4285       // extend already), the truncated to type is legal, sign_extend is legal
4286       // on that type, and the truncate to that type is both legal and free,
4287       // perform the transform.
4288       if ((ShiftAmt > 0) &&
4289           TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4290           TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4291           TLI.isTruncateFree(VT, TruncVT)) {
4292
4293           SDValue Amt = DAG.getConstant(ShiftAmt,
4294               getShiftAmountTy(N0.getOperand(0).getValueType()));
4295           SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
4296                                       N0.getOperand(0), Amt);
4297           SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
4298                                       Shift);
4299           return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
4300                              N->getValueType(0), Trunc);
4301       }
4302     }
4303   }
4304
4305   // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4306   if (N1.getOpcode() == ISD::TRUNCATE &&
4307       N1.getOperand(0).getOpcode() == ISD::AND) {
4308     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4309     if (NewOp1.getNode())
4310       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4311   }
4312
4313   // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4314   //      if c1 is equal to the number of bits the trunc removes
4315   if (N0.getOpcode() == ISD::TRUNCATE &&
4316       (N0.getOperand(0).getOpcode() == ISD::SRL ||
4317        N0.getOperand(0).getOpcode() == ISD::SRA) &&
4318       N0.getOperand(0).hasOneUse() &&
4319       N0.getOperand(0).getOperand(1).hasOneUse() &&
4320       N1C) {
4321     SDValue N0Op0 = N0.getOperand(0);
4322     if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4323       unsigned LargeShiftVal = LargeShift->getZExtValue();
4324       EVT LargeVT = N0Op0.getValueType();
4325
4326       if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4327         SDValue Amt =
4328           DAG.getConstant(LargeShiftVal + N1C->getZExtValue(),
4329                           getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4330         SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
4331                                   N0Op0.getOperand(0), Amt);
4332         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
4333       }
4334     }
4335   }
4336
4337   // Simplify, based on bits shifted out of the LHS.
4338   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4339     return SDValue(N, 0);
4340
4341
4342   // If the sign bit is known to be zero, switch this to a SRL.
4343   if (DAG.SignBitIsZero(N0))
4344     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4345
4346   if (N1C) {
4347     SDValue NewSRA = visitShiftByConstant(N, N1C);
4348     if (NewSRA.getNode())
4349       return NewSRA;
4350   }
4351
4352   return SDValue();
4353 }
4354
4355 SDValue DAGCombiner::visitSRL(SDNode *N) {
4356   SDValue N0 = N->getOperand(0);
4357   SDValue N1 = N->getOperand(1);
4358   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4359   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4360   EVT VT = N0.getValueType();
4361   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4362
4363   // fold vector ops
4364   if (VT.isVector()) {
4365     SDValue FoldedVOp = SimplifyVBinOp(N);
4366     if (FoldedVOp.getNode()) return FoldedVOp;
4367
4368     N1C = isConstOrConstSplat(N1);
4369   }
4370
4371   // fold (srl c1, c2) -> c1 >>u c2
4372   if (N0C && N1C)
4373     return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
4374   // fold (srl 0, x) -> 0
4375   if (N0C && N0C->isNullValue())
4376     return N0;
4377   // fold (srl x, c >= size(x)) -> undef
4378   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4379     return DAG.getUNDEF(VT);
4380   // fold (srl x, 0) -> x
4381   if (N1C && N1C->isNullValue())
4382     return N0;
4383   // if (srl x, c) is known to be zero, return 0
4384   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4385                                    APInt::getAllOnesValue(OpSizeInBits)))
4386     return DAG.getConstant(0, VT);
4387
4388   // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4389   if (N1C && N0.getOpcode() == ISD::SRL) {
4390     if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4391       uint64_t c1 = N01C->getZExtValue();
4392       uint64_t c2 = N1C->getZExtValue();
4393       if (c1 + c2 >= OpSizeInBits)
4394         return DAG.getConstant(0, VT);
4395       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4396                          DAG.getConstant(c1 + c2, N1.getValueType()));
4397     }
4398   }
4399
4400   // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4401   if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4402       N0.getOperand(0).getOpcode() == ISD::SRL &&
4403       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4404     uint64_t c1 =
4405       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4406     uint64_t c2 = N1C->getZExtValue();
4407     EVT InnerShiftVT = N0.getOperand(0).getValueType();
4408     EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4409     uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4410     // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4411     if (c1 + OpSizeInBits == InnerShiftSize) {
4412       if (c1 + c2 >= InnerShiftSize)
4413         return DAG.getConstant(0, VT);
4414       return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
4415                          DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
4416                                      N0.getOperand(0)->getOperand(0),
4417                                      DAG.getConstant(c1 + c2, ShiftCountVT)));
4418     }
4419   }
4420
4421   // fold (srl (shl x, c), c) -> (and x, cst2)
4422   if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4423     unsigned BitSize = N0.getScalarValueSizeInBits();
4424     if (BitSize <= 64) {
4425       uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4426       return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4427                          DAG.getConstant(~0ULL >> ShAmt, VT));
4428     }
4429   }
4430
4431   // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4432   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4433     // Shifting in all undef bits?
4434     EVT SmallVT = N0.getOperand(0).getValueType();
4435     unsigned BitSize = SmallVT.getScalarSizeInBits();
4436     if (N1C->getZExtValue() >= BitSize)
4437       return DAG.getUNDEF(VT);
4438
4439     if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4440       uint64_t ShiftAmt = N1C->getZExtValue();
4441       SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
4442                                        N0.getOperand(0),
4443                           DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
4444       AddToWorklist(SmallShift.getNode());
4445       APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4446       return DAG.getNode(ISD::AND, SDLoc(N), VT,
4447                          DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
4448                          DAG.getConstant(Mask, VT));
4449     }
4450   }
4451
4452   // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
4453   // bit, which is unmodified by sra.
4454   if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4455     if (N0.getOpcode() == ISD::SRA)
4456       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4457   }
4458
4459   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
4460   if (N1C && N0.getOpcode() == ISD::CTLZ &&
4461       N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4462     APInt KnownZero, KnownOne;
4463     DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
4464
4465     // If any of the input bits are KnownOne, then the input couldn't be all
4466     // zeros, thus the result of the srl will always be zero.
4467     if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
4468
4469     // If all of the bits input the to ctlz node are known to be zero, then
4470     // the result of the ctlz is "32" and the result of the shift is one.
4471     APInt UnknownBits = ~KnownZero;
4472     if (UnknownBits == 0) return DAG.getConstant(1, VT);
4473
4474     // Otherwise, check to see if there is exactly one bit input to the ctlz.
4475     if ((UnknownBits & (UnknownBits - 1)) == 0) {
4476       // Okay, we know that only that the single bit specified by UnknownBits
4477       // could be set on input to the CTLZ node. If this bit is set, the SRL
4478       // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4479       // to an SRL/XOR pair, which is likely to simplify more.
4480       unsigned ShAmt = UnknownBits.countTrailingZeros();
4481       SDValue Op = N0.getOperand(0);
4482
4483       if (ShAmt) {
4484         Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
4485                   DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
4486         AddToWorklist(Op.getNode());
4487       }
4488
4489       return DAG.getNode(ISD::XOR, SDLoc(N), VT,
4490                          Op, DAG.getConstant(1, VT));
4491     }
4492   }
4493
4494   // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4495   if (N1.getOpcode() == ISD::TRUNCATE &&
4496       N1.getOperand(0).getOpcode() == ISD::AND) {
4497     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4498     if (NewOp1.getNode())
4499       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4500   }
4501
4502   // fold operands of srl based on knowledge that the low bits are not
4503   // demanded.
4504   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4505     return SDValue(N, 0);
4506
4507   if (N1C) {
4508     SDValue NewSRL = visitShiftByConstant(N, N1C);
4509     if (NewSRL.getNode())
4510       return NewSRL;
4511   }
4512
4513   // Attempt to convert a srl of a load into a narrower zero-extending load.
4514   SDValue NarrowLoad = ReduceLoadWidth(N);
4515   if (NarrowLoad.getNode())
4516     return NarrowLoad;
4517
4518   // Here is a common situation. We want to optimize:
4519   //
4520   //   %a = ...
4521   //   %b = and i32 %a, 2
4522   //   %c = srl i32 %b, 1
4523   //   brcond i32 %c ...
4524   //
4525   // into
4526   //
4527   //   %a = ...
4528   //   %b = and %a, 2
4529   //   %c = setcc eq %b, 0
4530   //   brcond %c ...
4531   //
4532   // However when after the source operand of SRL is optimized into AND, the SRL
4533   // itself may not be optimized further. Look for it and add the BRCOND into
4534   // the worklist.
4535   if (N->hasOneUse()) {
4536     SDNode *Use = *N->use_begin();
4537     if (Use->getOpcode() == ISD::BRCOND)
4538       AddToWorklist(Use);
4539     else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4540       // Also look pass the truncate.
4541       Use = *Use->use_begin();
4542       if (Use->getOpcode() == ISD::BRCOND)
4543         AddToWorklist(Use);
4544     }
4545   }
4546
4547   return SDValue();
4548 }
4549
4550 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4551   SDValue N0 = N->getOperand(0);
4552   EVT VT = N->getValueType(0);
4553
4554   // fold (ctlz c1) -> c2
4555   if (isa<ConstantSDNode>(N0))
4556     return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4557   return SDValue();
4558 }
4559
4560 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4561   SDValue N0 = N->getOperand(0);
4562   EVT VT = N->getValueType(0);
4563
4564   // fold (ctlz_zero_undef c1) -> c2
4565   if (isa<ConstantSDNode>(N0))
4566     return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4567   return SDValue();
4568 }
4569
4570 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4571   SDValue N0 = N->getOperand(0);
4572   EVT VT = N->getValueType(0);
4573
4574   // fold (cttz c1) -> c2
4575   if (isa<ConstantSDNode>(N0))
4576     return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4577   return SDValue();
4578 }
4579
4580 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4581   SDValue N0 = N->getOperand(0);
4582   EVT VT = N->getValueType(0);
4583
4584   // fold (cttz_zero_undef c1) -> c2
4585   if (isa<ConstantSDNode>(N0))
4586     return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4587   return SDValue();
4588 }
4589
4590 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4591   SDValue N0 = N->getOperand(0);
4592   EVT VT = N->getValueType(0);
4593
4594   // fold (ctpop c1) -> c2
4595   if (isa<ConstantSDNode>(N0))
4596     return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4597   return SDValue();
4598 }
4599
4600 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4601   SDValue N0 = N->getOperand(0);
4602   SDValue N1 = N->getOperand(1);
4603   SDValue N2 = N->getOperand(2);
4604   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4605   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4606   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4607   EVT VT = N->getValueType(0);
4608   EVT VT0 = N0.getValueType();
4609
4610   // fold (select C, X, X) -> X
4611   if (N1 == N2)
4612     return N1;
4613   // fold (select true, X, Y) -> X
4614   if (N0C && !N0C->isNullValue())
4615     return N1;
4616   // fold (select false, X, Y) -> Y
4617   if (N0C && N0C->isNullValue())
4618     return N2;
4619   // fold (select C, 1, X) -> (or C, X)
4620   if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
4621     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4622   // fold (select C, 0, 1) -> (xor C, 1)
4623   // We can't do this reliably if integer based booleans have different contents
4624   // to floating point based booleans. This is because we can't tell whether we
4625   // have an integer-based boolean or a floating-point-based boolean unless we
4626   // can find the SETCC that produced it and inspect its operands. This is
4627   // fairly easy if C is the SETCC node, but it can potentially be
4628   // undiscoverable (or not reasonably discoverable). For example, it could be
4629   // in another basic block or it could require searching a complicated
4630   // expression.
4631   if (VT.isInteger() &&
4632       (VT0 == MVT::i1 || (VT0.isInteger() &&
4633                           TLI.getBooleanContents(false, false) ==
4634                               TLI.getBooleanContents(false, true) &&
4635                           TLI.getBooleanContents(false, false) ==
4636                               TargetLowering::ZeroOrOneBooleanContent)) &&
4637       N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
4638     SDValue XORNode;
4639     if (VT == VT0)
4640       return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
4641                          N0, DAG.getConstant(1, VT0));
4642     XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
4643                           N0, DAG.getConstant(1, VT0));
4644     AddToWorklist(XORNode.getNode());
4645     if (VT.bitsGT(VT0))
4646       return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4647     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4648   }
4649   // fold (select C, 0, X) -> (and (not C), X)
4650   if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
4651     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4652     AddToWorklist(NOTNode.getNode());
4653     return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4654   }
4655   // fold (select C, X, 1) -> (or (not C), X)
4656   if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4657     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4658     AddToWorklist(NOTNode.getNode());
4659     return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4660   }
4661   // fold (select C, X, 0) -> (and C, X)
4662   if (VT == MVT::i1 && N2C && N2C->isNullValue())
4663     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4664   // fold (select X, X, Y) -> (or X, Y)
4665   // fold (select X, 1, Y) -> (or X, Y)
4666   if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4667     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4668   // fold (select X, Y, X) -> (and X, Y)
4669   // fold (select X, Y, 0) -> (and X, Y)
4670   if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
4671     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4672
4673   // If we can fold this based on the true/false value, do so.
4674   if (SimplifySelectOps(N, N1, N2))
4675     return SDValue(N, 0);  // Don't revisit N.
4676
4677   // fold selects based on a setcc into other things, such as min/max/abs
4678   if (N0.getOpcode() == ISD::SETCC) {
4679     if ((!LegalOperations &&
4680          TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
4681         TLI.isOperationLegal(ISD::SELECT_CC, VT))
4682       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4683                          N0.getOperand(0), N0.getOperand(1),
4684                          N1, N2, N0.getOperand(2));
4685     return SimplifySelect(SDLoc(N), N0, N1, N2);
4686   }
4687
4688   return SDValue();
4689 }
4690
4691 static
4692 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
4693   SDLoc DL(N);
4694   EVT LoVT, HiVT;
4695   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
4696
4697   // Split the inputs.
4698   SDValue Lo, Hi, LL, LH, RL, RH;
4699   std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
4700   std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
4701
4702   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
4703   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
4704
4705   return std::make_pair(Lo, Hi);
4706 }
4707
4708 // This function assumes all the vselect's arguments are CONCAT_VECTOR
4709 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
4710 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
4711   SDLoc dl(N);
4712   SDValue Cond = N->getOperand(0);
4713   SDValue LHS = N->getOperand(1);
4714   SDValue RHS = N->getOperand(2);
4715   EVT VT = N->getValueType(0);
4716   int NumElems = VT.getVectorNumElements();
4717   assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
4718          RHS.getOpcode() == ISD::CONCAT_VECTORS &&
4719          Cond.getOpcode() == ISD::BUILD_VECTOR);
4720
4721   // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
4722   // binary ones here.
4723   if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
4724     return SDValue();
4725
4726   // We're sure we have an even number of elements due to the
4727   // concat_vectors we have as arguments to vselect.
4728   // Skip BV elements until we find one that's not an UNDEF
4729   // After we find an UNDEF element, keep looping until we get to half the
4730   // length of the BV and see if all the non-undef nodes are the same.
4731   ConstantSDNode *BottomHalf = nullptr;
4732   for (int i = 0; i < NumElems / 2; ++i) {
4733     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4734       continue;
4735
4736     if (BottomHalf == nullptr)
4737       BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4738     else if (Cond->getOperand(i).getNode() != BottomHalf)
4739       return SDValue();
4740   }
4741
4742   // Do the same for the second half of the BuildVector
4743   ConstantSDNode *TopHalf = nullptr;
4744   for (int i = NumElems / 2; i < NumElems; ++i) {
4745     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4746       continue;
4747
4748     if (TopHalf == nullptr)
4749       TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4750     else if (Cond->getOperand(i).getNode() != TopHalf)
4751       return SDValue();
4752   }
4753
4754   assert(TopHalf && BottomHalf &&
4755          "One half of the selector was all UNDEFs and the other was all the "
4756          "same value. This should have been addressed before this function.");
4757   return DAG.getNode(
4758       ISD::CONCAT_VECTORS, dl, VT,
4759       BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
4760       TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
4761 }
4762
4763 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
4764   SDValue N0 = N->getOperand(0);
4765   SDValue N1 = N->getOperand(1);
4766   SDValue N2 = N->getOperand(2);
4767   SDLoc DL(N);
4768
4769   // Canonicalize integer abs.
4770   // vselect (setg[te] X,  0),  X, -X ->
4771   // vselect (setgt    X, -1),  X, -X ->
4772   // vselect (setl[te] X,  0), -X,  X ->
4773   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
4774   if (N0.getOpcode() == ISD::SETCC) {
4775     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4776     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4777     bool isAbs = false;
4778     bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
4779
4780     if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
4781          (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
4782         N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
4783       isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
4784     else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
4785              N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
4786       isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4787
4788     if (isAbs) {
4789       EVT VT = LHS.getValueType();
4790       SDValue Shift = DAG.getNode(
4791           ISD::SRA, DL, VT, LHS,
4792           DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
4793       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
4794       AddToWorklist(Shift.getNode());
4795       AddToWorklist(Add.getNode());
4796       return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
4797     }
4798   }
4799
4800   // If the VSELECT result requires splitting and the mask is provided by a
4801   // SETCC, then split both nodes and its operands before legalization. This
4802   // prevents the type legalizer from unrolling SETCC into scalar comparisons
4803   // and enables future optimizations (e.g. min/max pattern matching on X86).
4804   if (N0.getOpcode() == ISD::SETCC) {
4805     EVT VT = N->getValueType(0);
4806
4807     // Check if any splitting is required.
4808     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
4809         TargetLowering::TypeSplitVector)
4810       return SDValue();
4811
4812     SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
4813     std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
4814     std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
4815     std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
4816
4817     Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
4818     Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
4819
4820     // Add the new VSELECT nodes to the work list in case they need to be split
4821     // again.
4822     AddToWorklist(Lo.getNode());
4823     AddToWorklist(Hi.getNode());
4824
4825     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
4826   }
4827
4828   // Fold (vselect (build_vector all_ones), N1, N2) -> N1
4829   if (ISD::isBuildVectorAllOnes(N0.getNode()))
4830     return N1;
4831   // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
4832   if (ISD::isBuildVectorAllZeros(N0.getNode()))
4833     return N2;
4834
4835   // The ConvertSelectToConcatVector function is assuming both the above
4836   // checks for (vselect (build_vector all{ones,zeros) ...) have been made
4837   // and addressed.
4838   if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
4839       N2.getOpcode() == ISD::CONCAT_VECTORS &&
4840       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
4841     SDValue CV = ConvertSelectToConcatVector(N, DAG);
4842     if (CV.getNode())
4843       return CV;
4844   }
4845
4846   return SDValue();
4847 }
4848
4849 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
4850   SDValue N0 = N->getOperand(0);
4851   SDValue N1 = N->getOperand(1);
4852   SDValue N2 = N->getOperand(2);
4853   SDValue N3 = N->getOperand(3);
4854   SDValue N4 = N->getOperand(4);
4855   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
4856
4857   // fold select_cc lhs, rhs, x, x, cc -> x
4858   if (N2 == N3)
4859     return N2;
4860
4861   // Determine if the condition we're dealing with is constant
4862   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
4863                               N0, N1, CC, SDLoc(N), false);
4864   if (SCC.getNode()) {
4865     AddToWorklist(SCC.getNode());
4866
4867     if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
4868       if (!SCCC->isNullValue())
4869         return N2;    // cond always true -> true val
4870       else
4871         return N3;    // cond always false -> false val
4872     }
4873
4874     // Fold to a simpler select_cc
4875     if (SCC.getOpcode() == ISD::SETCC)
4876       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
4877                          SCC.getOperand(0), SCC.getOperand(1), N2, N3,
4878                          SCC.getOperand(2));
4879   }
4880
4881   // If we can fold this based on the true/false value, do so.
4882   if (SimplifySelectOps(N, N2, N3))
4883     return SDValue(N, 0);  // Don't revisit N.
4884
4885   // fold select_cc into other things, such as min/max/abs
4886   return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
4887 }
4888
4889 SDValue DAGCombiner::visitSETCC(SDNode *N) {
4890   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
4891                        cast<CondCodeSDNode>(N->getOperand(2))->get(),
4892                        SDLoc(N));
4893 }
4894
4895 // tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
4896 // dag node into a ConstantSDNode or a build_vector of constants.
4897 // This function is called by the DAGCombiner when visiting sext/zext/aext
4898 // dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
4899 // Vector extends are not folded if operations are legal; this is to
4900 // avoid introducing illegal build_vector dag nodes.
4901 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
4902                                          SelectionDAG &DAG, bool LegalTypes,
4903                                          bool LegalOperations) {
4904   unsigned Opcode = N->getOpcode();
4905   SDValue N0 = N->getOperand(0);
4906   EVT VT = N->getValueType(0);
4907
4908   assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
4909          Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
4910
4911   // fold (sext c1) -> c1
4912   // fold (zext c1) -> c1
4913   // fold (aext c1) -> c1
4914   if (isa<ConstantSDNode>(N0))
4915     return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
4916
4917   // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
4918   // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
4919   // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
4920   EVT SVT = VT.getScalarType();
4921   if (!(VT.isVector() &&
4922       (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
4923       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
4924     return nullptr;
4925
4926   // We can fold this node into a build_vector.
4927   unsigned VTBits = SVT.getSizeInBits();
4928   unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
4929   unsigned ShAmt = VTBits - EVTBits;
4930   SmallVector<SDValue, 8> Elts;
4931   unsigned NumElts = N0->getNumOperands();
4932   SDLoc DL(N);
4933
4934   for (unsigned i=0; i != NumElts; ++i) {
4935     SDValue Op = N0->getOperand(i);
4936     if (Op->getOpcode() == ISD::UNDEF) {
4937       Elts.push_back(DAG.getUNDEF(SVT));
4938       continue;
4939     }
4940
4941     ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
4942     const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
4943     if (Opcode == ISD::SIGN_EXTEND)
4944       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
4945                                      SVT));
4946     else
4947       Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
4948                                      SVT));
4949   }
4950
4951   return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
4952 }
4953
4954 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
4955 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
4956 // transformation. Returns true if extension are possible and the above
4957 // mentioned transformation is profitable.
4958 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
4959                                     unsigned ExtOpc,
4960                                     SmallVectorImpl<SDNode *> &ExtendNodes,
4961                                     const TargetLowering &TLI) {
4962   bool HasCopyToRegUses = false;
4963   bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
4964   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
4965                             UE = N0.getNode()->use_end();
4966        UI != UE; ++UI) {
4967     SDNode *User = *UI;
4968     if (User == N)
4969       continue;
4970     if (UI.getUse().getResNo() != N0.getResNo())
4971       continue;
4972     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
4973     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
4974       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
4975       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
4976         // Sign bits will be lost after a zext.
4977         return false;
4978       bool Add = false;
4979       for (unsigned i = 0; i != 2; ++i) {
4980         SDValue UseOp = User->getOperand(i);
4981         if (UseOp == N0)
4982           continue;
4983         if (!isa<ConstantSDNode>(UseOp))
4984           return false;
4985         Add = true;
4986       }
4987       if (Add)
4988         ExtendNodes.push_back(User);
4989       continue;
4990     }
4991     // If truncates aren't free and there are users we can't
4992     // extend, it isn't worthwhile.
4993     if (!isTruncFree)
4994       return false;
4995     // Remember if this value is live-out.
4996     if (User->getOpcode() == ISD::CopyToReg)
4997       HasCopyToRegUses = true;
4998   }
4999
5000   if (HasCopyToRegUses) {
5001     bool BothLiveOut = false;
5002     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
5003          UI != UE; ++UI) {
5004       SDUse &Use = UI.getUse();
5005       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
5006         BothLiveOut = true;
5007         break;
5008       }
5009     }
5010     if (BothLiveOut)
5011       // Both unextended and extended values are live out. There had better be
5012       // a good reason for the transformation.
5013       return ExtendNodes.size();
5014   }
5015   return true;
5016 }
5017
5018 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
5019                                   SDValue Trunc, SDValue ExtLoad, SDLoc DL,
5020                                   ISD::NodeType ExtType) {
5021   // Extend SetCC uses if necessary.
5022   for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
5023     SDNode *SetCC = SetCCs[i];
5024     SmallVector<SDValue, 4> Ops;
5025
5026     for (unsigned j = 0; j != 2; ++j) {
5027       SDValue SOp = SetCC->getOperand(j);
5028       if (SOp == Trunc)
5029         Ops.push_back(ExtLoad);
5030       else
5031         Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
5032     }
5033
5034     Ops.push_back(SetCC->getOperand(2));
5035     CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
5036   }
5037 }
5038
5039 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
5040   SDValue N0 = N->getOperand(0);
5041   EVT VT = N->getValueType(0);
5042
5043   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5044                                               LegalOperations))
5045     return SDValue(Res, 0);
5046
5047   // fold (sext (sext x)) -> (sext x)
5048   // fold (sext (aext x)) -> (sext x)
5049   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5050     return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
5051                        N0.getOperand(0));
5052
5053   if (N0.getOpcode() == ISD::TRUNCATE) {
5054     // fold (sext (truncate (load x))) -> (sext (smaller load x))
5055     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
5056     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5057     if (NarrowLoad.getNode()) {
5058       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5059       if (NarrowLoad.getNode() != N0.getNode()) {
5060         CombineTo(N0.getNode(), NarrowLoad);
5061         // CombineTo deleted the truncate, if needed, but not what's under it.
5062         AddToWorklist(oye);
5063       }
5064       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5065     }
5066
5067     // See if the value being truncated is already sign extended.  If so, just
5068     // eliminate the trunc/sext pair.
5069     SDValue Op = N0.getOperand(0);
5070     unsigned OpBits   = Op.getValueType().getScalarType().getSizeInBits();
5071     unsigned MidBits  = N0.getValueType().getScalarType().getSizeInBits();
5072     unsigned DestBits = VT.getScalarType().getSizeInBits();
5073     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
5074
5075     if (OpBits == DestBits) {
5076       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
5077       // bits, it is already ready.
5078       if (NumSignBits > DestBits-MidBits)
5079         return Op;
5080     } else if (OpBits < DestBits) {
5081       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
5082       // bits, just sext from i32.
5083       if (NumSignBits > OpBits-MidBits)
5084         return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
5085     } else {
5086       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
5087       // bits, just truncate to i32.
5088       if (NumSignBits > OpBits-MidBits)
5089         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5090     }
5091
5092     // fold (sext (truncate x)) -> (sextinreg x).
5093     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
5094                                                  N0.getValueType())) {
5095       if (OpBits < DestBits)
5096         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
5097       else if (OpBits > DestBits)
5098         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
5099       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
5100                          DAG.getValueType(N0.getValueType()));
5101     }
5102   }
5103
5104   // fold (sext (load x)) -> (sext (truncate (sextload x)))
5105   // None of the supported targets knows how to perform load and sign extend
5106   // on vectors in one instruction.  We only perform this transformation on
5107   // scalars.
5108   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5109       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5110       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5111        TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
5112     bool DoXform = true;
5113     SmallVector<SDNode*, 4> SetCCs;
5114     if (!N0.hasOneUse())
5115       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
5116     if (DoXform) {
5117       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5118       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5119                                        LN0->getChain(),
5120                                        LN0->getBasePtr(), N0.getValueType(),
5121                                        LN0->getMemOperand());
5122       CombineTo(N, ExtLoad);
5123       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5124                                   N0.getValueType(), ExtLoad);
5125       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5126       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5127                       ISD::SIGN_EXTEND);
5128       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5129     }
5130   }
5131
5132   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
5133   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
5134   if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5135       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5136     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5137     EVT MemVT = LN0->getMemoryVT();
5138     if ((!LegalOperations && !LN0->isVolatile()) ||
5139         TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
5140       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5141                                        LN0->getChain(),
5142                                        LN0->getBasePtr(), MemVT,
5143                                        LN0->getMemOperand());
5144       CombineTo(N, ExtLoad);
5145       CombineTo(N0.getNode(),
5146                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5147                             N0.getValueType(), ExtLoad),
5148                 ExtLoad.getValue(1));
5149       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5150     }
5151   }
5152
5153   // fold (sext (and/or/xor (load x), cst)) ->
5154   //      (and/or/xor (sextload x), (sext cst))
5155   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5156        N0.getOpcode() == ISD::XOR) &&
5157       isa<LoadSDNode>(N0.getOperand(0)) &&
5158       N0.getOperand(1).getOpcode() == ISD::Constant &&
5159       TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) &&
5160       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5161     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5162     if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
5163       bool DoXform = true;
5164       SmallVector<SDNode*, 4> SetCCs;
5165       if (!N0.hasOneUse())
5166         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
5167                                           SetCCs, TLI);
5168       if (DoXform) {
5169         SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
5170                                          LN0->getChain(), LN0->getBasePtr(),
5171                                          LN0->getMemoryVT(),
5172                                          LN0->getMemOperand());
5173         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5174         Mask = Mask.sext(VT.getSizeInBits());
5175         SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5176                                   ExtLoad, DAG.getConstant(Mask, VT));
5177         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5178                                     SDLoc(N0.getOperand(0)),
5179                                     N0.getOperand(0).getValueType(), ExtLoad);
5180         CombineTo(N, And);
5181         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5182         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5183                         ISD::SIGN_EXTEND);
5184         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5185       }
5186     }
5187   }
5188
5189   if (N0.getOpcode() == ISD::SETCC) {
5190     EVT N0VT = N0.getOperand(0).getValueType();
5191     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
5192     // Only do this before legalize for now.
5193     if (VT.isVector() && !LegalOperations &&
5194         TLI.getBooleanContents(N0VT) ==
5195             TargetLowering::ZeroOrNegativeOneBooleanContent) {
5196       // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5197       // of the same size as the compared operands. Only optimize sext(setcc())
5198       // if this is the case.
5199       EVT SVT = getSetCCResultType(N0VT);
5200
5201       // We know that the # elements of the results is the same as the
5202       // # elements of the compare (and the # elements of the compare result
5203       // for that matter).  Check to see that they are the same size.  If so,
5204       // we know that the element size of the sext'd result matches the
5205       // element size of the compare operands.
5206       if (VT.getSizeInBits() == SVT.getSizeInBits())
5207         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5208                              N0.getOperand(1),
5209                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
5210
5211       // If the desired elements are smaller or larger than the source
5212       // elements we can use a matching integer vector type and then
5213       // truncate/sign extend
5214       EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5215       if (SVT == MatchingVectorType) {
5216         SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
5217                                N0.getOperand(0), N0.getOperand(1),
5218                                cast<CondCodeSDNode>(N0.getOperand(2))->get());
5219         return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5220       }
5221     }
5222
5223     // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
5224     unsigned ElementWidth = VT.getScalarType().getSizeInBits();
5225     SDValue NegOne =
5226       DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
5227     SDValue SCC =
5228       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5229                        NegOne, DAG.getConstant(0, VT),
5230                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5231     if (SCC.getNode()) return SCC;
5232
5233     if (!VT.isVector()) {
5234       EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
5235       if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
5236         SDLoc DL(N);
5237         ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5238         SDValue SetCC = DAG.getSetCC(DL, SetCCVT,
5239                                      N0.getOperand(0), N0.getOperand(1), CC);
5240         return DAG.getSelect(DL, VT, SetCC,
5241                              NegOne, DAG.getConstant(0, VT));
5242       }
5243     }
5244   }
5245
5246   // fold (sext x) -> (zext x) if the sign bit is known zero.
5247   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
5248       DAG.SignBitIsZero(N0))
5249     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
5250
5251   return SDValue();
5252 }
5253
5254 // isTruncateOf - If N is a truncate of some other value, return true, record
5255 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
5256 // This function computes KnownZero to avoid a duplicated call to
5257 // computeKnownBits in the caller.
5258 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
5259                          APInt &KnownZero) {
5260   APInt KnownOne;
5261   if (N->getOpcode() == ISD::TRUNCATE) {
5262     Op = N->getOperand(0);
5263     DAG.computeKnownBits(Op, KnownZero, KnownOne);
5264     return true;
5265   }
5266
5267   if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
5268       cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
5269     return false;
5270
5271   SDValue Op0 = N->getOperand(0);
5272   SDValue Op1 = N->getOperand(1);
5273   assert(Op0.getValueType() == Op1.getValueType());
5274
5275   ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
5276   ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
5277   if (COp0 && COp0->isNullValue())
5278     Op = Op1;
5279   else if (COp1 && COp1->isNullValue())
5280     Op = Op0;
5281   else
5282     return false;
5283
5284   DAG.computeKnownBits(Op, KnownZero, KnownOne);
5285
5286   if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
5287     return false;
5288
5289   return true;
5290 }
5291
5292 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
5293   SDValue N0 = N->getOperand(0);
5294   EVT VT = N->getValueType(0);
5295
5296   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5297                                               LegalOperations))
5298     return SDValue(Res, 0);
5299
5300   // fold (zext (zext x)) -> (zext x)
5301   // fold (zext (aext x)) -> (zext x)
5302   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5303     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
5304                        N0.getOperand(0));
5305
5306   // fold (zext (truncate x)) -> (zext x) or
5307   //      (zext (truncate x)) -> (truncate x)
5308   // This is valid when the truncated bits of x are already zero.
5309   // FIXME: We should extend this to work for vectors too.
5310   SDValue Op;
5311   APInt KnownZero;
5312   if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
5313     APInt TruncatedBits =
5314       (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
5315       APInt(Op.getValueSizeInBits(), 0) :
5316       APInt::getBitsSet(Op.getValueSizeInBits(),
5317                         N0.getValueSizeInBits(),
5318                         std::min(Op.getValueSizeInBits(),
5319                                  VT.getSizeInBits()));
5320     if (TruncatedBits == (KnownZero & TruncatedBits)) {
5321       if (VT.bitsGT(Op.getValueType()))
5322         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
5323       if (VT.bitsLT(Op.getValueType()))
5324         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5325
5326       return Op;
5327     }
5328   }
5329
5330   // fold (zext (truncate (load x))) -> (zext (smaller load x))
5331   // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
5332   if (N0.getOpcode() == ISD::TRUNCATE) {
5333     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5334     if (NarrowLoad.getNode()) {
5335       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5336       if (NarrowLoad.getNode() != N0.getNode()) {
5337         CombineTo(N0.getNode(), NarrowLoad);
5338         // CombineTo deleted the truncate, if needed, but not what's under it.
5339         AddToWorklist(oye);
5340       }
5341       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5342     }
5343   }
5344
5345   // fold (zext (truncate x)) -> (and x, mask)
5346   if (N0.getOpcode() == ISD::TRUNCATE &&
5347       (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
5348
5349     // fold (zext (truncate (load x))) -> (zext (smaller load x))
5350     // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
5351     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5352     if (NarrowLoad.getNode()) {
5353       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5354       if (NarrowLoad.getNode() != N0.getNode()) {
5355         CombineTo(N0.getNode(), NarrowLoad);
5356         // CombineTo deleted the truncate, if needed, but not what's under it.
5357         AddToWorklist(oye);
5358       }
5359       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5360     }
5361
5362     SDValue Op = N0.getOperand(0);
5363     if (Op.getValueType().bitsLT(VT)) {
5364       Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
5365       AddToWorklist(Op.getNode());
5366     } else if (Op.getValueType().bitsGT(VT)) {
5367       Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5368       AddToWorklist(Op.getNode());
5369     }
5370     return DAG.getZeroExtendInReg(Op, SDLoc(N),
5371                                   N0.getValueType().getScalarType());
5372   }
5373
5374   // Fold (zext (and (trunc x), cst)) -> (and x, cst),
5375   // if either of the casts is not free.
5376   if (N0.getOpcode() == ISD::AND &&
5377       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5378       N0.getOperand(1).getOpcode() == ISD::Constant &&
5379       (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5380                            N0.getValueType()) ||
5381        !TLI.isZExtFree(N0.getValueType(), VT))) {
5382     SDValue X = N0.getOperand(0).getOperand(0);
5383     if (X.getValueType().bitsLT(VT)) {
5384       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
5385     } else if (X.getValueType().bitsGT(VT)) {
5386       X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
5387     }
5388     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5389     Mask = Mask.zext(VT.getSizeInBits());
5390     return DAG.getNode(ISD::AND, SDLoc(N), VT,
5391                        X, DAG.getConstant(Mask, VT));
5392   }
5393
5394   // fold (zext (load x)) -> (zext (truncate (zextload x)))
5395   // None of the supported targets knows how to perform load and vector_zext
5396   // on vectors in one instruction.  We only perform this transformation on
5397   // scalars.
5398   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5399       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5400       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5401        TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
5402     bool DoXform = true;
5403     SmallVector<SDNode*, 4> SetCCs;
5404     if (!N0.hasOneUse())
5405       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
5406     if (DoXform) {
5407       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5408       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5409                                        LN0->getChain(),
5410                                        LN0->getBasePtr(), N0.getValueType(),
5411                                        LN0->getMemOperand());
5412       CombineTo(N, ExtLoad);
5413       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5414                                   N0.getValueType(), ExtLoad);
5415       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5416
5417       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5418                       ISD::ZERO_EXTEND);
5419       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5420     }
5421   }
5422
5423   // fold (zext (and/or/xor (load x), cst)) ->
5424   //      (and/or/xor (zextload x), (zext cst))
5425   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5426        N0.getOpcode() == ISD::XOR) &&
5427       isa<LoadSDNode>(N0.getOperand(0)) &&
5428       N0.getOperand(1).getOpcode() == ISD::Constant &&
5429       TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) &&
5430       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5431     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5432     if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
5433       bool DoXform = true;
5434       SmallVector<SDNode*, 4> SetCCs;
5435       if (!N0.hasOneUse())
5436         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
5437                                           SetCCs, TLI);
5438       if (DoXform) {
5439         SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
5440                                          LN0->getChain(), LN0->getBasePtr(),
5441                                          LN0->getMemoryVT(),
5442                                          LN0->getMemOperand());
5443         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5444         Mask = Mask.zext(VT.getSizeInBits());
5445         SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5446                                   ExtLoad, DAG.getConstant(Mask, VT));
5447         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5448                                     SDLoc(N0.getOperand(0)),
5449                                     N0.getOperand(0).getValueType(), ExtLoad);
5450         CombineTo(N, And);
5451         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5452         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5453                         ISD::ZERO_EXTEND);
5454         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5455       }
5456     }
5457   }
5458
5459   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
5460   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
5461   if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5462       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5463     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5464     EVT MemVT = LN0->getMemoryVT();
5465     if ((!LegalOperations && !LN0->isVolatile()) ||
5466         TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
5467       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5468                                        LN0->getChain(),
5469                                        LN0->getBasePtr(), MemVT,
5470                                        LN0->getMemOperand());
5471       CombineTo(N, ExtLoad);
5472       CombineTo(N0.getNode(),
5473                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
5474                             ExtLoad),
5475                 ExtLoad.getValue(1));
5476       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5477     }
5478   }
5479
5480   if (N0.getOpcode() == ISD::SETCC) {
5481     if (!LegalOperations && VT.isVector() &&
5482         N0.getValueType().getVectorElementType() == MVT::i1) {
5483       EVT N0VT = N0.getOperand(0).getValueType();
5484       if (getSetCCResultType(N0VT) == N0.getValueType())
5485         return SDValue();
5486
5487       // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
5488       // Only do this before legalize for now.
5489       EVT EltVT = VT.getVectorElementType();
5490       SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
5491                                     DAG.getConstant(1, EltVT));
5492       if (VT.getSizeInBits() == N0VT.getSizeInBits())
5493         // We know that the # elements of the results is the same as the
5494         // # elements of the compare (and the # elements of the compare result
5495         // for that matter).  Check to see that they are the same size.  If so,
5496         // we know that the element size of the sext'd result matches the
5497         // element size of the compare operands.
5498         return DAG.getNode(ISD::AND, SDLoc(N), VT,
5499                            DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5500                                          N0.getOperand(1),
5501                                  cast<CondCodeSDNode>(N0.getOperand(2))->get()),
5502                            DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
5503                                        OneOps));
5504
5505       // If the desired elements are smaller or larger than the source
5506       // elements we can use a matching integer vector type and then
5507       // truncate/sign extend
5508       EVT MatchingElementType =
5509         EVT::getIntegerVT(*DAG.getContext(),
5510                           N0VT.getScalarType().getSizeInBits());
5511       EVT MatchingVectorType =
5512         EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5513                          N0VT.getVectorNumElements());
5514       SDValue VsetCC =
5515         DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5516                       N0.getOperand(1),
5517                       cast<CondCodeSDNode>(N0.getOperand(2))->get());
5518       return DAG.getNode(ISD::AND, SDLoc(N), VT,
5519                          DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
5520                          DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, OneOps));
5521     }
5522
5523     // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5524     SDValue SCC =
5525       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5526                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5527                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5528     if (SCC.getNode()) return SCC;
5529   }
5530
5531   // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
5532   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
5533       isa<ConstantSDNode>(N0.getOperand(1)) &&
5534       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
5535       N0.hasOneUse()) {
5536     SDValue ShAmt = N0.getOperand(1);
5537     unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
5538     if (N0.getOpcode() == ISD::SHL) {
5539       SDValue InnerZExt = N0.getOperand(0);
5540       // If the original shl may be shifting out bits, do not perform this
5541       // transformation.
5542       unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
5543         InnerZExt.getOperand(0).getValueType().getSizeInBits();
5544       if (ShAmtVal > KnownZeroBits)
5545         return SDValue();
5546     }
5547
5548     SDLoc DL(N);
5549
5550     // Ensure that the shift amount is wide enough for the shifted value.
5551     if (VT.getSizeInBits() >= 256)
5552       ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
5553
5554     return DAG.getNode(N0.getOpcode(), DL, VT,
5555                        DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
5556                        ShAmt);
5557   }
5558
5559   return SDValue();
5560 }
5561
5562 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
5563   SDValue N0 = N->getOperand(0);
5564   EVT VT = N->getValueType(0);
5565
5566   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5567                                               LegalOperations))
5568     return SDValue(Res, 0);
5569
5570   // fold (aext (aext x)) -> (aext x)
5571   // fold (aext (zext x)) -> (zext x)
5572   // fold (aext (sext x)) -> (sext x)
5573   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
5574       N0.getOpcode() == ISD::ZERO_EXTEND ||
5575       N0.getOpcode() == ISD::SIGN_EXTEND)
5576     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
5577
5578   // fold (aext (truncate (load x))) -> (aext (smaller load x))
5579   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
5580   if (N0.getOpcode() == ISD::TRUNCATE) {
5581     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5582     if (NarrowLoad.getNode()) {
5583       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5584       if (NarrowLoad.getNode() != N0.getNode()) {
5585         CombineTo(N0.getNode(), NarrowLoad);
5586         // CombineTo deleted the truncate, if needed, but not what's under it.
5587         AddToWorklist(oye);
5588       }
5589       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5590     }
5591   }
5592
5593   // fold (aext (truncate x))
5594   if (N0.getOpcode() == ISD::TRUNCATE) {
5595     SDValue TruncOp = N0.getOperand(0);
5596     if (TruncOp.getValueType() == VT)
5597       return TruncOp; // x iff x size == zext size.
5598     if (TruncOp.getValueType().bitsGT(VT))
5599       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
5600     return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
5601   }
5602
5603   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
5604   // if the trunc is not free.
5605   if (N0.getOpcode() == ISD::AND &&
5606       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5607       N0.getOperand(1).getOpcode() == ISD::Constant &&
5608       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5609                           N0.getValueType())) {
5610     SDValue X = N0.getOperand(0).getOperand(0);
5611     if (X.getValueType().bitsLT(VT)) {
5612       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
5613     } else if (X.getValueType().bitsGT(VT)) {
5614       X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
5615     }
5616     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5617     Mask = Mask.zext(VT.getSizeInBits());
5618     return DAG.getNode(ISD::AND, SDLoc(N), VT,
5619                        X, DAG.getConstant(Mask, VT));
5620   }
5621
5622   // fold (aext (load x)) -> (aext (truncate (extload x)))
5623   // None of the supported targets knows how to perform load and any_ext
5624   // on vectors in one instruction.  We only perform this transformation on
5625   // scalars.
5626   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5627       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5628       TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType())) {
5629     bool DoXform = true;
5630     SmallVector<SDNode*, 4> SetCCs;
5631     if (!N0.hasOneUse())
5632       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
5633     if (DoXform) {
5634       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5635       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
5636                                        LN0->getChain(),
5637                                        LN0->getBasePtr(), N0.getValueType(),
5638                                        LN0->getMemOperand());
5639       CombineTo(N, ExtLoad);
5640       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5641                                   N0.getValueType(), ExtLoad);
5642       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5643       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5644                       ISD::ANY_EXTEND);
5645       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5646     }
5647   }
5648
5649   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
5650   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
5651   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
5652   if (N0.getOpcode() == ISD::LOAD &&
5653       !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5654       N0.hasOneUse()) {
5655     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5656     ISD::LoadExtType ExtType = LN0->getExtensionType();
5657     EVT MemVT = LN0->getMemoryVT();
5658     if (!LegalOperations || TLI.isLoadExtLegal(ExtType, MemVT)) {
5659       SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
5660                                        VT, LN0->getChain(), LN0->getBasePtr(),
5661                                        MemVT, LN0->getMemOperand());
5662       CombineTo(N, ExtLoad);
5663       CombineTo(N0.getNode(),
5664                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5665                             N0.getValueType(), ExtLoad),
5666                 ExtLoad.getValue(1));
5667       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5668     }
5669   }
5670
5671   if (N0.getOpcode() == ISD::SETCC) {
5672     // For vectors:
5673     // aext(setcc) -> vsetcc
5674     // aext(setcc) -> truncate(vsetcc)
5675     // aext(setcc) -> aext(vsetcc)
5676     // Only do this before legalize for now.
5677     if (VT.isVector() && !LegalOperations) {
5678       EVT N0VT = N0.getOperand(0).getValueType();
5679         // We know that the # elements of the results is the same as the
5680         // # elements of the compare (and the # elements of the compare result
5681         // for that matter).  Check to see that they are the same size.  If so,
5682         // we know that the element size of the sext'd result matches the
5683         // element size of the compare operands.
5684       if (VT.getSizeInBits() == N0VT.getSizeInBits())
5685         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5686                              N0.getOperand(1),
5687                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
5688       // If the desired elements are smaller or larger than the source
5689       // elements we can use a matching integer vector type and then
5690       // truncate/any extend
5691       else {
5692         EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5693         SDValue VsetCC =
5694           DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5695                         N0.getOperand(1),
5696                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
5697         return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
5698       }
5699     }
5700
5701     // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5702     SDValue SCC =
5703       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5704                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5705                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5706     if (SCC.getNode())
5707       return SCC;
5708   }
5709
5710   return SDValue();
5711 }
5712
5713 /// See if the specified operand can be simplified with the knowledge that only
5714 /// the bits specified by Mask are used.  If so, return the simpler operand,
5715 /// otherwise return a null SDValue.
5716 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
5717   switch (V.getOpcode()) {
5718   default: break;
5719   case ISD::Constant: {
5720     const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
5721     assert(CV && "Const value should be ConstSDNode.");
5722     const APInt &CVal = CV->getAPIntValue();
5723     APInt NewVal = CVal & Mask;
5724     if (NewVal != CVal)
5725       return DAG.getConstant(NewVal, V.getValueType());
5726     break;
5727   }
5728   case ISD::OR:
5729   case ISD::XOR:
5730     // If the LHS or RHS don't contribute bits to the or, drop them.
5731     if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
5732       return V.getOperand(1);
5733     if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
5734       return V.getOperand(0);
5735     break;
5736   case ISD::SRL:
5737     // Only look at single-use SRLs.
5738     if (!V.getNode()->hasOneUse())
5739       break;
5740     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
5741       // See if we can recursively simplify the LHS.
5742       unsigned Amt = RHSC->getZExtValue();
5743
5744       // Watch out for shift count overflow though.
5745       if (Amt >= Mask.getBitWidth()) break;
5746       APInt NewMask = Mask << Amt;
5747       SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
5748       if (SimplifyLHS.getNode())
5749         return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
5750                            SimplifyLHS, V.getOperand(1));
5751     }
5752   }
5753   return SDValue();
5754 }
5755
5756 /// If the result of a wider load is shifted to right of N  bits and then
5757 /// truncated to a narrower type and where N is a multiple of number of bits of
5758 /// the narrower type, transform it to a narrower load from address + N / num of
5759 /// bits of new type. If the result is to be extended, also fold the extension
5760 /// to form a extending load.
5761 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
5762   unsigned Opc = N->getOpcode();
5763
5764   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
5765   SDValue N0 = N->getOperand(0);
5766   EVT VT = N->getValueType(0);
5767   EVT ExtVT = VT;
5768
5769   // This transformation isn't valid for vector loads.
5770   if (VT.isVector())
5771     return SDValue();
5772
5773   // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
5774   // extended to VT.
5775   if (Opc == ISD::SIGN_EXTEND_INREG) {
5776     ExtType = ISD::SEXTLOAD;
5777     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
5778   } else if (Opc == ISD::SRL) {
5779     // Another special-case: SRL is basically zero-extending a narrower value.
5780     ExtType = ISD::ZEXTLOAD;
5781     N0 = SDValue(N, 0);
5782     ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5783     if (!N01) return SDValue();
5784     ExtVT = EVT::getIntegerVT(*DAG.getContext(),
5785                               VT.getSizeInBits() - N01->getZExtValue());
5786   }
5787   if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT))
5788     return SDValue();
5789
5790   unsigned EVTBits = ExtVT.getSizeInBits();
5791
5792   // Do not generate loads of non-round integer types since these can
5793   // be expensive (and would be wrong if the type is not byte sized).
5794   if (!ExtVT.isRound())
5795     return SDValue();
5796
5797   unsigned ShAmt = 0;
5798   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
5799     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5800       ShAmt = N01->getZExtValue();
5801       // Is the shift amount a multiple of size of VT?
5802       if ((ShAmt & (EVTBits-1)) == 0) {
5803         N0 = N0.getOperand(0);
5804         // Is the load width a multiple of size of VT?
5805         if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
5806           return SDValue();
5807       }
5808
5809       // At this point, we must have a load or else we can't do the transform.
5810       if (!isa<LoadSDNode>(N0)) return SDValue();
5811
5812       // Because a SRL must be assumed to *need* to zero-extend the high bits
5813       // (as opposed to anyext the high bits), we can't combine the zextload
5814       // lowering of SRL and an sextload.
5815       if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
5816         return SDValue();
5817
5818       // If the shift amount is larger than the input type then we're not
5819       // accessing any of the loaded bytes.  If the load was a zextload/extload
5820       // then the result of the shift+trunc is zero/undef (handled elsewhere).
5821       if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
5822         return SDValue();
5823     }
5824   }
5825
5826   // If the load is shifted left (and the result isn't shifted back right),
5827   // we can fold the truncate through the shift.
5828   unsigned ShLeftAmt = 0;
5829   if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
5830       ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
5831     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5832       ShLeftAmt = N01->getZExtValue();
5833       N0 = N0.getOperand(0);
5834     }
5835   }
5836
5837   // If we haven't found a load, we can't narrow it.  Don't transform one with
5838   // multiple uses, this would require adding a new load.
5839   if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
5840     return SDValue();
5841
5842   // Don't change the width of a volatile load.
5843   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5844   if (LN0->isVolatile())
5845     return SDValue();
5846
5847   // Verify that we are actually reducing a load width here.
5848   if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
5849     return SDValue();
5850
5851   // For the transform to be legal, the load must produce only two values
5852   // (the value loaded and the chain).  Don't transform a pre-increment
5853   // load, for example, which produces an extra value.  Otherwise the
5854   // transformation is not equivalent, and the downstream logic to replace
5855   // uses gets things wrong.
5856   if (LN0->getNumValues() > 2)
5857     return SDValue();
5858
5859   // If the load that we're shrinking is an extload and we're not just
5860   // discarding the extension we can't simply shrink the load. Bail.
5861   // TODO: It would be possible to merge the extensions in some cases.
5862   if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
5863       LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
5864     return SDValue();
5865
5866   EVT PtrType = N0.getOperand(1).getValueType();
5867
5868   if (PtrType == MVT::Untyped || PtrType.isExtended())
5869     // It's not possible to generate a constant of extended or untyped type.
5870     return SDValue();
5871
5872   // For big endian targets, we need to adjust the offset to the pointer to
5873   // load the correct bytes.
5874   if (TLI.isBigEndian()) {
5875     unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
5876     unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
5877     ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
5878   }
5879
5880   uint64_t PtrOff = ShAmt / 8;
5881   unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
5882   SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
5883                                PtrType, LN0->getBasePtr(),
5884                                DAG.getConstant(PtrOff, PtrType));
5885   AddToWorklist(NewPtr.getNode());
5886
5887   SDValue Load;
5888   if (ExtType == ISD::NON_EXTLOAD)
5889     Load =  DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
5890                         LN0->getPointerInfo().getWithOffset(PtrOff),
5891                         LN0->isVolatile(), LN0->isNonTemporal(),
5892                         LN0->isInvariant(), NewAlign, LN0->getAAInfo());
5893   else
5894     Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
5895                           LN0->getPointerInfo().getWithOffset(PtrOff),
5896                           ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
5897                           LN0->isInvariant(), NewAlign, LN0->getAAInfo());
5898
5899   // Replace the old load's chain with the new load's chain.
5900   WorklistRemover DeadNodes(*this);
5901   DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
5902
5903   // Shift the result left, if we've swallowed a left shift.
5904   SDValue Result = Load;
5905   if (ShLeftAmt != 0) {
5906     EVT ShImmTy = getShiftAmountTy(Result.getValueType());
5907     if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
5908       ShImmTy = VT;
5909     // If the shift amount is as large as the result size (but, presumably,
5910     // no larger than the source) then the useful bits of the result are
5911     // zero; we can't simply return the shortened shift, because the result
5912     // of that operation is undefined.
5913     if (ShLeftAmt >= VT.getSizeInBits())
5914       Result = DAG.getConstant(0, VT);
5915     else
5916       Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
5917                           Result, DAG.getConstant(ShLeftAmt, ShImmTy));
5918   }
5919
5920   // Return the new loaded value.
5921   return Result;
5922 }
5923
5924 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
5925   SDValue N0 = N->getOperand(0);
5926   SDValue N1 = N->getOperand(1);
5927   EVT VT = N->getValueType(0);
5928   EVT EVT = cast<VTSDNode>(N1)->getVT();
5929   unsigned VTBits = VT.getScalarType().getSizeInBits();
5930   unsigned EVTBits = EVT.getScalarType().getSizeInBits();
5931
5932   // fold (sext_in_reg c1) -> c1
5933   if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
5934     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
5935
5936   // If the input is already sign extended, just drop the extension.
5937   if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
5938     return N0;
5939
5940   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
5941   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
5942       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
5943     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5944                        N0.getOperand(0), N1);
5945
5946   // fold (sext_in_reg (sext x)) -> (sext x)
5947   // fold (sext_in_reg (aext x)) -> (sext x)
5948   // if x is small enough.
5949   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
5950     SDValue N00 = N0.getOperand(0);
5951     if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
5952         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
5953       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
5954   }
5955
5956   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
5957   if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
5958     return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
5959
5960   // fold operands of sext_in_reg based on knowledge that the top bits are not
5961   // demanded.
5962   if (SimplifyDemandedBits(SDValue(N, 0)))
5963     return SDValue(N, 0);
5964
5965   // fold (sext_in_reg (load x)) -> (smaller sextload x)
5966   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
5967   SDValue NarrowLoad = ReduceLoadWidth(N);
5968   if (NarrowLoad.getNode())
5969     return NarrowLoad;
5970
5971   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
5972   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
5973   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
5974   if (N0.getOpcode() == ISD::SRL) {
5975     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
5976       if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
5977         // We can turn this into an SRA iff the input to the SRL is already sign
5978         // extended enough.
5979         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
5980         if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
5981           return DAG.getNode(ISD::SRA, SDLoc(N), VT,
5982                              N0.getOperand(0), N0.getOperand(1));
5983       }
5984   }
5985
5986   // fold (sext_inreg (extload x)) -> (sextload x)
5987   if (ISD::isEXTLoad(N0.getNode()) &&
5988       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5989       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5990       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5991        TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5992     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5993     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5994                                      LN0->getChain(),
5995                                      LN0->getBasePtr(), EVT,
5996                                      LN0->getMemOperand());
5997     CombineTo(N, ExtLoad);
5998     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5999     AddToWorklist(ExtLoad.getNode());
6000     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6001   }
6002   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
6003   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6004       N0.hasOneUse() &&
6005       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6006       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6007        TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
6008     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6009     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6010                                      LN0->getChain(),
6011                                      LN0->getBasePtr(), EVT,
6012                                      LN0->getMemOperand());
6013     CombineTo(N, ExtLoad);
6014     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6015     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6016   }
6017
6018   // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
6019   if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
6020     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
6021                                        N0.getOperand(1), false);
6022     if (BSwap.getNode())
6023       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6024                          BSwap, N1);
6025   }
6026
6027   // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
6028   // into a build_vector.
6029   if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
6030     SmallVector<SDValue, 8> Elts;
6031     unsigned NumElts = N0->getNumOperands();
6032     unsigned ShAmt = VTBits - EVTBits;
6033
6034     for (unsigned i = 0; i != NumElts; ++i) {
6035       SDValue Op = N0->getOperand(i);
6036       if (Op->getOpcode() == ISD::UNDEF) {
6037         Elts.push_back(Op);
6038         continue;
6039       }
6040
6041       ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
6042       const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
6043       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
6044                                      Op.getValueType()));
6045     }
6046
6047     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts);
6048   }
6049
6050   return SDValue();
6051 }
6052
6053 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
6054   SDValue N0 = N->getOperand(0);
6055   EVT VT = N->getValueType(0);
6056   bool isLE = TLI.isLittleEndian();
6057
6058   // noop truncate
6059   if (N0.getValueType() == N->getValueType(0))
6060     return N0;
6061   // fold (truncate c1) -> c1
6062   if (isa<ConstantSDNode>(N0))
6063     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
6064   // fold (truncate (truncate x)) -> (truncate x)
6065   if (N0.getOpcode() == ISD::TRUNCATE)
6066     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6067   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
6068   if (N0.getOpcode() == ISD::ZERO_EXTEND ||
6069       N0.getOpcode() == ISD::SIGN_EXTEND ||
6070       N0.getOpcode() == ISD::ANY_EXTEND) {
6071     if (N0.getOperand(0).getValueType().bitsLT(VT))
6072       // if the source is smaller than the dest, we still need an extend
6073       return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
6074                          N0.getOperand(0));
6075     if (N0.getOperand(0).getValueType().bitsGT(VT))
6076       // if the source is larger than the dest, than we just need the truncate
6077       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6078     // if the source and dest are the same type, we can drop both the extend
6079     // and the truncate.
6080     return N0.getOperand(0);
6081   }
6082
6083   // Fold extract-and-trunc into a narrow extract. For example:
6084   //   i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
6085   //   i32 y = TRUNCATE(i64 x)
6086   //        -- becomes --
6087   //   v16i8 b = BITCAST (v2i64 val)
6088   //   i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
6089   //
6090   // Note: We only run this optimization after type legalization (which often
6091   // creates this pattern) and before operation legalization after which
6092   // we need to be more careful about the vector instructions that we generate.
6093   if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6094       LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
6095
6096     EVT VecTy = N0.getOperand(0).getValueType();
6097     EVT ExTy = N0.getValueType();
6098     EVT TrTy = N->getValueType(0);
6099
6100     unsigned NumElem = VecTy.getVectorNumElements();
6101     unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
6102
6103     EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
6104     assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
6105
6106     SDValue EltNo = N0->getOperand(1);
6107     if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
6108       int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6109       EVT IndexTy = TLI.getVectorIdxTy();
6110       int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
6111
6112       SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
6113                               NVT, N0.getOperand(0));
6114
6115       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
6116                          SDLoc(N), TrTy, V,
6117                          DAG.getConstant(Index, IndexTy));
6118     }
6119   }
6120
6121   // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
6122   if (N0.getOpcode() == ISD::SELECT) {
6123     EVT SrcVT = N0.getValueType();
6124     if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
6125         TLI.isTruncateFree(SrcVT, VT)) {
6126       SDLoc SL(N0);
6127       SDValue Cond = N0.getOperand(0);
6128       SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
6129       SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
6130       return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
6131     }
6132   }
6133
6134   // Fold a series of buildvector, bitcast, and truncate if possible.
6135   // For example fold
6136   //   (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
6137   //   (2xi32 (buildvector x, y)).
6138   if (Level == AfterLegalizeVectorOps && VT.isVector() &&
6139       N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
6140       N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
6141       N0.getOperand(0).hasOneUse()) {
6142
6143     SDValue BuildVect = N0.getOperand(0);
6144     EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
6145     EVT TruncVecEltTy = VT.getVectorElementType();
6146
6147     // Check that the element types match.
6148     if (BuildVectEltTy == TruncVecEltTy) {
6149       // Now we only need to compute the offset of the truncated elements.
6150       unsigned BuildVecNumElts =  BuildVect.getNumOperands();
6151       unsigned TruncVecNumElts = VT.getVectorNumElements();
6152       unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
6153
6154       assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
6155              "Invalid number of elements");
6156
6157       SmallVector<SDValue, 8> Opnds;
6158       for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
6159         Opnds.push_back(BuildVect.getOperand(i));
6160
6161       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
6162     }
6163   }
6164
6165   // See if we can simplify the input to this truncate through knowledge that
6166   // only the low bits are being used.
6167   // For example "trunc (or (shl x, 8), y)" // -> trunc y
6168   // Currently we only perform this optimization on scalars because vectors
6169   // may have different active low bits.
6170   if (!VT.isVector()) {
6171     SDValue Shorter =
6172       GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
6173                                                VT.getSizeInBits()));
6174     if (Shorter.getNode())
6175       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
6176   }
6177   // fold (truncate (load x)) -> (smaller load x)
6178   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
6179   if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
6180     SDValue Reduced = ReduceLoadWidth(N);
6181     if (Reduced.getNode())
6182       return Reduced;
6183     // Handle the case where the load remains an extending load even
6184     // after truncation.
6185     if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
6186       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6187       if (!LN0->isVolatile() &&
6188           LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
6189         SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
6190                                          VT, LN0->getChain(), LN0->getBasePtr(),
6191                                          LN0->getMemoryVT(),
6192                                          LN0->getMemOperand());
6193         DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
6194         return NewLoad;
6195       }
6196     }
6197   }
6198   // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
6199   // where ... are all 'undef'.
6200   if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
6201     SmallVector<EVT, 8> VTs;
6202     SDValue V;
6203     unsigned Idx = 0;
6204     unsigned NumDefs = 0;
6205
6206     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
6207       SDValue X = N0.getOperand(i);
6208       if (X.getOpcode() != ISD::UNDEF) {
6209         V = X;
6210         Idx = i;
6211         NumDefs++;
6212       }
6213       // Stop if more than one members are non-undef.
6214       if (NumDefs > 1)
6215         break;
6216       VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
6217                                      VT.getVectorElementType(),
6218                                      X.getValueType().getVectorNumElements()));
6219     }
6220
6221     if (NumDefs == 0)
6222       return DAG.getUNDEF(VT);
6223
6224     if (NumDefs == 1) {
6225       assert(V.getNode() && "The single defined operand is empty!");
6226       SmallVector<SDValue, 8> Opnds;
6227       for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
6228         if (i != Idx) {
6229           Opnds.push_back(DAG.getUNDEF(VTs[i]));
6230           continue;
6231         }
6232         SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
6233         AddToWorklist(NV.getNode());
6234         Opnds.push_back(NV);
6235       }
6236       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
6237     }
6238   }
6239
6240   // Simplify the operands using demanded-bits information.
6241   if (!VT.isVector() &&
6242       SimplifyDemandedBits(SDValue(N, 0)))
6243     return SDValue(N, 0);
6244
6245   return SDValue();
6246 }
6247
6248 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
6249   SDValue Elt = N->getOperand(i);
6250   if (Elt.getOpcode() != ISD::MERGE_VALUES)
6251     return Elt.getNode();
6252   return Elt.getOperand(Elt.getResNo()).getNode();
6253 }
6254
6255 /// build_pair (load, load) -> load
6256 /// if load locations are consecutive.
6257 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
6258   assert(N->getOpcode() == ISD::BUILD_PAIR);
6259
6260   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
6261   LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
6262   if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
6263       LD1->getAddressSpace() != LD2->getAddressSpace())
6264     return SDValue();
6265   EVT LD1VT = LD1->getValueType(0);
6266
6267   if (ISD::isNON_EXTLoad(LD2) &&
6268       LD2->hasOneUse() &&
6269       // If both are volatile this would reduce the number of volatile loads.
6270       // If one is volatile it might be ok, but play conservative and bail out.
6271       !LD1->isVolatile() &&
6272       !LD2->isVolatile() &&
6273       DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
6274     unsigned Align = LD1->getAlignment();
6275     unsigned NewAlign = TLI.getDataLayout()->
6276       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6277
6278     if (NewAlign <= Align &&
6279         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
6280       return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
6281                          LD1->getBasePtr(), LD1->getPointerInfo(),
6282                          false, false, false, Align);
6283   }
6284
6285   return SDValue();
6286 }
6287
6288 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
6289   SDValue N0 = N->getOperand(0);
6290   EVT VT = N->getValueType(0);
6291
6292   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
6293   // Only do this before legalize, since afterward the target may be depending
6294   // on the bitconvert.
6295   // First check to see if this is all constant.
6296   if (!LegalTypes &&
6297       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
6298       VT.isVector()) {
6299     bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
6300
6301     EVT DestEltVT = N->getValueType(0).getVectorElementType();
6302     assert(!DestEltVT.isVector() &&
6303            "Element type of vector ValueType must not be vector!");
6304     if (isSimple)
6305       return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
6306   }
6307
6308   // If the input is a constant, let getNode fold it.
6309   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
6310     SDValue Res = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
6311     if (Res.getNode() != N) {
6312       if (!LegalOperations ||
6313           TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
6314         return Res;
6315
6316       // Folding it resulted in an illegal node, and it's too late to
6317       // do that. Clean up the old node and forego the transformation.
6318       // Ideally this won't happen very often, because instcombine
6319       // and the earlier dagcombine runs (where illegal nodes are
6320       // permitted) should have folded most of them already.
6321       deleteAndRecombine(Res.getNode());
6322     }
6323   }
6324
6325   // (conv (conv x, t1), t2) -> (conv x, t2)
6326   if (N0.getOpcode() == ISD::BITCAST)
6327     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
6328                        N0.getOperand(0));
6329
6330   // fold (conv (load x)) -> (load (conv*)x)
6331   // If the resultant load doesn't need a higher alignment than the original!
6332   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
6333       // Do not change the width of a volatile load.
6334       !cast<LoadSDNode>(N0)->isVolatile() &&
6335       // Do not remove the cast if the types differ in endian layout.
6336       TLI.hasBigEndianPartOrdering(N0.getValueType()) ==
6337       TLI.hasBigEndianPartOrdering(VT) &&
6338       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
6339       TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
6340     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6341     unsigned Align = TLI.getDataLayout()->
6342       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6343     unsigned OrigAlign = LN0->getAlignment();
6344
6345     if (Align <= OrigAlign) {
6346       SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
6347                                  LN0->getBasePtr(), LN0->getPointerInfo(),
6348                                  LN0->isVolatile(), LN0->isNonTemporal(),
6349                                  LN0->isInvariant(), OrigAlign,
6350                                  LN0->getAAInfo());
6351       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6352       return Load;
6353     }
6354   }
6355
6356   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6357   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
6358   // This often reduces constant pool loads.
6359   if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
6360        (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
6361       N0.getNode()->hasOneUse() && VT.isInteger() &&
6362       !VT.isVector() && !N0.getValueType().isVector()) {
6363     SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
6364                                   N0.getOperand(0));
6365     AddToWorklist(NewConv.getNode());
6366
6367     APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6368     if (N0.getOpcode() == ISD::FNEG)
6369       return DAG.getNode(ISD::XOR, SDLoc(N), VT,
6370                          NewConv, DAG.getConstant(SignBit, VT));
6371     assert(N0.getOpcode() == ISD::FABS);
6372     return DAG.getNode(ISD::AND, SDLoc(N), VT,
6373                        NewConv, DAG.getConstant(~SignBit, VT));
6374   }
6375
6376   // fold (bitconvert (fcopysign cst, x)) ->
6377   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
6378   // Note that we don't handle (copysign x, cst) because this can always be
6379   // folded to an fneg or fabs.
6380   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
6381       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
6382       VT.isInteger() && !VT.isVector()) {
6383     unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
6384     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
6385     if (isTypeLegal(IntXVT)) {
6386       SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6387                               IntXVT, N0.getOperand(1));
6388       AddToWorklist(X.getNode());
6389
6390       // If X has a different width than the result/lhs, sext it or truncate it.
6391       unsigned VTWidth = VT.getSizeInBits();
6392       if (OrigXWidth < VTWidth) {
6393         X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
6394         AddToWorklist(X.getNode());
6395       } else if (OrigXWidth > VTWidth) {
6396         // To get the sign bit in the right place, we have to shift it right
6397         // before truncating.
6398         X = DAG.getNode(ISD::SRL, SDLoc(X),
6399                         X.getValueType(), X,
6400                         DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
6401         AddToWorklist(X.getNode());
6402         X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6403         AddToWorklist(X.getNode());
6404       }
6405
6406       APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6407       X = DAG.getNode(ISD::AND, SDLoc(X), VT,
6408                       X, DAG.getConstant(SignBit, VT));
6409       AddToWorklist(X.getNode());
6410
6411       SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6412                                 VT, N0.getOperand(0));
6413       Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
6414                         Cst, DAG.getConstant(~SignBit, VT));
6415       AddToWorklist(Cst.getNode());
6416
6417       return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
6418     }
6419   }
6420
6421   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
6422   if (N0.getOpcode() == ISD::BUILD_PAIR) {
6423     SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
6424     if (CombineLD.getNode())
6425       return CombineLD;
6426   }
6427
6428   return SDValue();
6429 }
6430
6431 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
6432   EVT VT = N->getValueType(0);
6433   return CombineConsecutiveLoads(N, VT);
6434 }
6435
6436 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
6437 /// operands. DstEltVT indicates the destination element value type.
6438 SDValue DAGCombiner::
6439 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
6440   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
6441
6442   // If this is already the right type, we're done.
6443   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
6444
6445   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
6446   unsigned DstBitSize = DstEltVT.getSizeInBits();
6447
6448   // If this is a conversion of N elements of one type to N elements of another
6449   // type, convert each element.  This handles FP<->INT cases.
6450   if (SrcBitSize == DstBitSize) {
6451     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6452                               BV->getValueType(0).getVectorNumElements());
6453
6454     // Due to the FP element handling below calling this routine recursively,
6455     // we can end up with a scalar-to-vector node here.
6456     if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
6457       return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6458                          DAG.getNode(ISD::BITCAST, SDLoc(BV),
6459                                      DstEltVT, BV->getOperand(0)));
6460
6461     SmallVector<SDValue, 8> Ops;
6462     for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6463       SDValue Op = BV->getOperand(i);
6464       // If the vector element type is not legal, the BUILD_VECTOR operands
6465       // are promoted and implicitly truncated.  Make that explicit here.
6466       if (Op.getValueType() != SrcEltVT)
6467         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
6468       Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
6469                                 DstEltVT, Op));
6470       AddToWorklist(Ops.back().getNode());
6471     }
6472     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6473   }
6474
6475   // Otherwise, we're growing or shrinking the elements.  To avoid having to
6476   // handle annoying details of growing/shrinking FP values, we convert them to
6477   // int first.
6478   if (SrcEltVT.isFloatingPoint()) {
6479     // Convert the input float vector to a int vector where the elements are the
6480     // same sizes.
6481     assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
6482     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
6483     BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
6484     SrcEltVT = IntVT;
6485   }
6486
6487   // Now we know the input is an integer vector.  If the output is a FP type,
6488   // convert to integer first, then to FP of the right size.
6489   if (DstEltVT.isFloatingPoint()) {
6490     assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
6491     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
6492     SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
6493
6494     // Next, convert to FP elements of the same size.
6495     return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
6496   }
6497
6498   // Okay, we know the src/dst types are both integers of differing types.
6499   // Handling growing first.
6500   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
6501   if (SrcBitSize < DstBitSize) {
6502     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
6503
6504     SmallVector<SDValue, 8> Ops;
6505     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
6506          i += NumInputsPerOutput) {
6507       bool isLE = TLI.isLittleEndian();
6508       APInt NewBits = APInt(DstBitSize, 0);
6509       bool EltIsUndef = true;
6510       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
6511         // Shift the previously computed bits over.
6512         NewBits <<= SrcBitSize;
6513         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
6514         if (Op.getOpcode() == ISD::UNDEF) continue;
6515         EltIsUndef = false;
6516
6517         NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
6518                    zextOrTrunc(SrcBitSize).zext(DstBitSize);
6519       }
6520
6521       if (EltIsUndef)
6522         Ops.push_back(DAG.getUNDEF(DstEltVT));
6523       else
6524         Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
6525     }
6526
6527     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
6528     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6529   }
6530
6531   // Finally, this must be the case where we are shrinking elements: each input
6532   // turns into multiple outputs.
6533   bool isS2V = ISD::isScalarToVector(BV);
6534   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
6535   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6536                             NumOutputsPerInput*BV->getNumOperands());
6537   SmallVector<SDValue, 8> Ops;
6538
6539   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6540     if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
6541       for (unsigned j = 0; j != NumOutputsPerInput; ++j)
6542         Ops.push_back(DAG.getUNDEF(DstEltVT));
6543       continue;
6544     }
6545
6546     APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
6547                   getAPIntValue().zextOrTrunc(SrcBitSize);
6548
6549     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
6550       APInt ThisVal = OpVal.trunc(DstBitSize);
6551       Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
6552       if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
6553         // Simply turn this into a SCALAR_TO_VECTOR of the new type.
6554         return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6555                            Ops[0]);
6556       OpVal = OpVal.lshr(DstBitSize);
6557     }
6558
6559     // For big endian targets, swap the order of the pieces of each element.
6560     if (TLI.isBigEndian())
6561       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
6562   }
6563
6564   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6565 }
6566
6567 SDValue DAGCombiner::visitFADD(SDNode *N) {
6568   SDValue N0 = N->getOperand(0);
6569   SDValue N1 = N->getOperand(1);
6570   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6571   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6572   EVT VT = N->getValueType(0);
6573   const TargetOptions &Options = DAG.getTarget().Options;
6574
6575   // fold vector ops
6576   if (VT.isVector()) {
6577     SDValue FoldedVOp = SimplifyVBinOp(N);
6578     if (FoldedVOp.getNode()) return FoldedVOp;
6579   }
6580
6581   // fold (fadd c1, c2) -> c1 + c2
6582   if (N0CFP && N1CFP)
6583     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
6584
6585   // canonicalize constant to RHS
6586   if (N0CFP && !N1CFP)
6587     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
6588
6589   // fold (fadd A, (fneg B)) -> (fsub A, B)
6590   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6591       isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
6592     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
6593                        GetNegatedExpression(N1, DAG, LegalOperations));
6594
6595   // fold (fadd (fneg A), B) -> (fsub B, A)
6596   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6597       isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
6598     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
6599                        GetNegatedExpression(N0, DAG, LegalOperations));
6600
6601   // If 'unsafe math' is enabled, fold lots of things.
6602   if (Options.UnsafeFPMath) {
6603     // No FP constant should be created after legalization as Instruction
6604     // Selection pass has a hard time dealing with FP constants.
6605     bool AllowNewConst = (Level < AfterLegalizeDAG);
6606
6607     // fold (fadd A, 0) -> A
6608     if (N1CFP && N1CFP->getValueAPF().isZero())
6609       return N0;
6610
6611     // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
6612     if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
6613         isa<ConstantFPSDNode>(N0.getOperand(1)))
6614       return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
6615                          DAG.getNode(ISD::FADD, SDLoc(N), VT,
6616                                      N0.getOperand(1), N1));
6617
6618     // If allowed, fold (fadd (fneg x), x) -> 0.0
6619     if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
6620       return DAG.getConstantFP(0.0, VT);
6621
6622     // If allowed, fold (fadd x, (fneg x)) -> 0.0
6623     if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
6624       return DAG.getConstantFP(0.0, VT);
6625
6626     // We can fold chains of FADD's of the same value into multiplications.
6627     // This transform is not safe in general because we are reducing the number
6628     // of rounding steps.
6629     if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
6630       if (N0.getOpcode() == ISD::FMUL) {
6631         ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6632         ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6633
6634         // (fadd (fmul x, c), x) -> (fmul x, c+1)
6635         if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
6636           SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6637                                        SDValue(CFP01, 0),
6638                                        DAG.getConstantFP(1.0, VT));
6639           return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, NewCFP);
6640         }
6641
6642         // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
6643         if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
6644             N1.getOperand(0) == N1.getOperand(1) &&
6645             N0.getOperand(0) == N1.getOperand(0)) {
6646           SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6647                                        SDValue(CFP01, 0),
6648                                        DAG.getConstantFP(2.0, VT));
6649           return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6650                              N0.getOperand(0), NewCFP);
6651         }
6652       }
6653
6654       if (N1.getOpcode() == ISD::FMUL) {
6655         ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6656         ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
6657
6658         // (fadd x, (fmul x, c)) -> (fmul x, c+1)
6659         if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
6660           SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6661                                        SDValue(CFP11, 0),
6662                                        DAG.getConstantFP(1.0, VT));
6663           return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, NewCFP);
6664         }
6665
6666         // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
6667         if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
6668             N0.getOperand(0) == N0.getOperand(1) &&
6669             N1.getOperand(0) == N0.getOperand(0)) {
6670           SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6671                                        SDValue(CFP11, 0),
6672                                        DAG.getConstantFP(2.0, VT));
6673           return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1.getOperand(0), NewCFP);
6674         }
6675       }
6676
6677       if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
6678         ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6679         // (fadd (fadd x, x), x) -> (fmul x, 3.0)
6680         if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
6681             (N0.getOperand(0) == N1))
6682           return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6683                              N1, DAG.getConstantFP(3.0, VT));
6684       }
6685
6686       if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
6687         ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6688         // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
6689         if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
6690             N1.getOperand(0) == N0)
6691           return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6692                              N0, DAG.getConstantFP(3.0, VT));
6693       }
6694
6695       // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
6696       if (AllowNewConst &&
6697           N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
6698           N0.getOperand(0) == N0.getOperand(1) &&
6699           N1.getOperand(0) == N1.getOperand(1) &&
6700           N0.getOperand(0) == N1.getOperand(0))
6701         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6702                            N0.getOperand(0), DAG.getConstantFP(4.0, VT));
6703     }
6704   } // enable-unsafe-fp-math
6705
6706   // FADD -> FMA combines:
6707   if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) &&
6708       TLI.isFMAFasterThanFMulAndFAdd(VT) &&
6709       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6710
6711     // fold (fadd (fmul x, y), z) -> (fma x, y, z)
6712     if (N0.getOpcode() == ISD::FMUL &&
6713         (N0->hasOneUse() || TLI.enableAggressiveFMAFusion(VT)))
6714       return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6715                          N0.getOperand(0), N0.getOperand(1), N1);
6716
6717     // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
6718     // Note: Commutes FADD operands.
6719     if (N1.getOpcode() == ISD::FMUL &&
6720         (N1->hasOneUse() || TLI.enableAggressiveFMAFusion(VT)))
6721       return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6722                          N1.getOperand(0), N1.getOperand(1), N0);
6723   }
6724
6725   return SDValue();
6726 }
6727
6728 SDValue DAGCombiner::visitFSUB(SDNode *N) {
6729   SDValue N0 = N->getOperand(0);
6730   SDValue N1 = N->getOperand(1);
6731   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
6732   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
6733   EVT VT = N->getValueType(0);
6734   SDLoc dl(N);
6735   const TargetOptions &Options = DAG.getTarget().Options;
6736
6737   // fold vector ops
6738   if (VT.isVector()) {
6739     SDValue FoldedVOp = SimplifyVBinOp(N);
6740     if (FoldedVOp.getNode()) return FoldedVOp;
6741   }
6742
6743   // fold (fsub c1, c2) -> c1-c2
6744   if (N0CFP && N1CFP)
6745     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
6746
6747   // fold (fsub A, (fneg B)) -> (fadd A, B)
6748   if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
6749     return DAG.getNode(ISD::FADD, dl, VT, N0,
6750                        GetNegatedExpression(N1, DAG, LegalOperations));
6751
6752   // If 'unsafe math' is enabled, fold lots of things.
6753   if (Options.UnsafeFPMath) {
6754     // (fsub A, 0) -> A
6755     if (N1CFP && N1CFP->getValueAPF().isZero())
6756       return N0;
6757
6758     // (fsub 0, B) -> -B
6759     if (N0CFP && N0CFP->getValueAPF().isZero()) {
6760       if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
6761         return GetNegatedExpression(N1, DAG, LegalOperations);
6762       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6763         return DAG.getNode(ISD::FNEG, dl, VT, N1);
6764     }
6765
6766     // (fsub x, x) -> 0.0
6767     if (N0 == N1)
6768       return DAG.getConstantFP(0.0f, VT);
6769
6770     // (fsub x, (fadd x, y)) -> (fneg y)
6771     // (fsub x, (fadd y, x)) -> (fneg y)
6772     if (N1.getOpcode() == ISD::FADD) {
6773       SDValue N10 = N1->getOperand(0);
6774       SDValue N11 = N1->getOperand(1);
6775
6776       if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
6777         return GetNegatedExpression(N11, DAG, LegalOperations);
6778
6779       if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
6780         return GetNegatedExpression(N10, DAG, LegalOperations);
6781     }
6782   }
6783
6784   // FSUB -> FMA combines:
6785   if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) &&
6786       TLI.isFMAFasterThanFMulAndFAdd(VT) &&
6787       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6788
6789     // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
6790     if (N0.getOpcode() == ISD::FMUL &&
6791         (N0->hasOneUse() || TLI.enableAggressiveFMAFusion(VT)))
6792       return DAG.getNode(ISD::FMA, dl, VT,
6793                          N0.getOperand(0), N0.getOperand(1),
6794                          DAG.getNode(ISD::FNEG, dl, VT, N1));
6795
6796     // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
6797     // Note: Commutes FSUB operands.
6798     if (N1.getOpcode() == ISD::FMUL &&
6799         (N1->hasOneUse() || TLI.enableAggressiveFMAFusion(VT)))
6800       return DAG.getNode(ISD::FMA, dl, VT,
6801                          DAG.getNode(ISD::FNEG, dl, VT,
6802                          N1.getOperand(0)),
6803                          N1.getOperand(1), N0);
6804
6805     // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
6806     if (N0.getOpcode() == ISD::FNEG &&
6807         N0.getOperand(0).getOpcode() == ISD::FMUL &&
6808         ((N0->hasOneUse() && N0.getOperand(0).hasOneUse()) ||
6809             TLI.enableAggressiveFMAFusion(VT))) {
6810       SDValue N00 = N0.getOperand(0).getOperand(0);
6811       SDValue N01 = N0.getOperand(0).getOperand(1);
6812       return DAG.getNode(ISD::FMA, dl, VT,
6813                          DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
6814                          DAG.getNode(ISD::FNEG, dl, VT, N1));
6815     }
6816   }
6817
6818   return SDValue();
6819 }
6820
6821 SDValue DAGCombiner::visitFMUL(SDNode *N) {
6822   SDValue N0 = N->getOperand(0);
6823   SDValue N1 = N->getOperand(1);
6824   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
6825   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
6826   EVT VT = N->getValueType(0);
6827   const TargetOptions &Options = DAG.getTarget().Options;
6828
6829   // fold vector ops
6830   if (VT.isVector()) {
6831     // This just handles C1 * C2 for vectors. Other vector folds are below.
6832     SDValue FoldedVOp = SimplifyVBinOp(N);
6833     if (FoldedVOp.getNode())
6834       return FoldedVOp;
6835     // Canonicalize vector constant to RHS.
6836     if (N0.getOpcode() == ISD::BUILD_VECTOR &&
6837         N1.getOpcode() != ISD::BUILD_VECTOR)
6838       if (auto *BV0 = dyn_cast<BuildVectorSDNode>(N0))
6839         if (BV0->isConstant())
6840           return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0);
6841   }
6842
6843   // fold (fmul c1, c2) -> c1*c2
6844   if (N0CFP && N1CFP)
6845     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
6846
6847   // canonicalize constant to RHS
6848   if (N0CFP && !N1CFP)
6849     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
6850
6851   // fold (fmul A, 1.0) -> A
6852   if (N1CFP && N1CFP->isExactlyValue(1.0))
6853     return N0;
6854
6855   if (Options.UnsafeFPMath) {
6856     // fold (fmul A, 0) -> 0
6857     if (N1CFP && N1CFP->getValueAPF().isZero())
6858       return N1;
6859
6860     // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
6861     if (N0.getOpcode() == ISD::FMUL) {
6862       // Fold scalars or any vector constants (not just splats).
6863       // This fold is done in general by InstCombine, but extra fmul insts
6864       // may have been generated during lowering.
6865       SDValue N01 = N0.getOperand(1);
6866       auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
6867       auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
6868       if ((N1CFP && isConstOrConstSplatFP(N01)) ||
6869           (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
6870         SDLoc SL(N);
6871         SDValue MulConsts = DAG.getNode(ISD::FMUL, SL, VT, N01, N1);
6872         return DAG.getNode(ISD::FMUL, SL, VT, N0.getOperand(0), MulConsts);
6873       }
6874     }
6875
6876     // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
6877     // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
6878     // during an early run of DAGCombiner can prevent folding with fmuls
6879     // inserted during lowering.
6880     if (N0.getOpcode() == ISD::FADD && N0.getOperand(0) == N0.getOperand(1)) {
6881       SDLoc SL(N);
6882       const SDValue Two = DAG.getConstantFP(2.0, VT);
6883       SDValue MulConsts = DAG.getNode(ISD::FMUL, SL, VT, Two, N1);
6884       return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0), MulConsts);
6885     }
6886   }
6887
6888   // fold (fmul X, 2.0) -> (fadd X, X)
6889   if (N1CFP && N1CFP->isExactlyValue(+2.0))
6890     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
6891
6892   // fold (fmul X, -1.0) -> (fneg X)
6893   if (N1CFP && N1CFP->isExactlyValue(-1.0))
6894     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6895       return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
6896
6897   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
6898   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
6899     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
6900       // Both can be negated for free, check to see if at least one is cheaper
6901       // negated.
6902       if (LHSNeg == 2 || RHSNeg == 2)
6903         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6904                            GetNegatedExpression(N0, DAG, LegalOperations),
6905                            GetNegatedExpression(N1, DAG, LegalOperations));
6906     }
6907   }
6908
6909   return SDValue();
6910 }
6911
6912 SDValue DAGCombiner::visitFMA(SDNode *N) {
6913   SDValue N0 = N->getOperand(0);
6914   SDValue N1 = N->getOperand(1);
6915   SDValue N2 = N->getOperand(2);
6916   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6917   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6918   EVT VT = N->getValueType(0);
6919   SDLoc dl(N);
6920   const TargetOptions &Options = DAG.getTarget().Options;
6921
6922   // Constant fold FMA.
6923   if (isa<ConstantFPSDNode>(N0) &&
6924       isa<ConstantFPSDNode>(N1) &&
6925       isa<ConstantFPSDNode>(N2)) {
6926     return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
6927   }
6928
6929   if (Options.UnsafeFPMath) {
6930     if (N0CFP && N0CFP->isZero())
6931       return N2;
6932     if (N1CFP && N1CFP->isZero())
6933       return N2;
6934   }
6935   if (N0CFP && N0CFP->isExactlyValue(1.0))
6936     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
6937   if (N1CFP && N1CFP->isExactlyValue(1.0))
6938     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
6939
6940   // Canonicalize (fma c, x, y) -> (fma x, c, y)
6941   if (N0CFP && !N1CFP)
6942     return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
6943
6944   // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
6945   if (Options.UnsafeFPMath && N1CFP &&
6946       N2.getOpcode() == ISD::FMUL &&
6947       N0 == N2.getOperand(0) &&
6948       N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
6949     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6950                        DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
6951   }
6952
6953
6954   // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
6955   if (Options.UnsafeFPMath &&
6956       N0.getOpcode() == ISD::FMUL && N1CFP &&
6957       N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
6958     return DAG.getNode(ISD::FMA, dl, VT,
6959                        N0.getOperand(0),
6960                        DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
6961                        N2);
6962   }
6963
6964   // (fma x, 1, y) -> (fadd x, y)
6965   // (fma x, -1, y) -> (fadd (fneg x), y)
6966   if (N1CFP) {
6967     if (N1CFP->isExactlyValue(1.0))
6968       return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
6969
6970     if (N1CFP->isExactlyValue(-1.0) &&
6971         (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
6972       SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
6973       AddToWorklist(RHSNeg.getNode());
6974       return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
6975     }
6976   }
6977
6978   // (fma x, c, x) -> (fmul x, (c+1))
6979   if (Options.UnsafeFPMath && N1CFP && N0 == N2)
6980     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6981                        DAG.getNode(ISD::FADD, dl, VT,
6982                                    N1, DAG.getConstantFP(1.0, VT)));
6983
6984   // (fma x, c, (fneg x)) -> (fmul x, (c-1))
6985   if (Options.UnsafeFPMath && N1CFP &&
6986       N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
6987     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6988                        DAG.getNode(ISD::FADD, dl, VT,
6989                                    N1, DAG.getConstantFP(-1.0, VT)));
6990
6991
6992   return SDValue();
6993 }
6994
6995 SDValue DAGCombiner::visitFDIV(SDNode *N) {
6996   SDValue N0 = N->getOperand(0);
6997   SDValue N1 = N->getOperand(1);
6998   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6999   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7000   EVT VT = N->getValueType(0);
7001   SDLoc DL(N);
7002   const TargetOptions &Options = DAG.getTarget().Options;
7003
7004   // fold vector ops
7005   if (VT.isVector()) {
7006     SDValue FoldedVOp = SimplifyVBinOp(N);
7007     if (FoldedVOp.getNode()) return FoldedVOp;
7008   }
7009
7010   // fold (fdiv c1, c2) -> c1/c2
7011   if (N0CFP && N1CFP)
7012     return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
7013
7014   if (Options.UnsafeFPMath) {
7015     // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
7016     if (N1CFP) {
7017       // Compute the reciprocal 1.0 / c2.
7018       APFloat N1APF = N1CFP->getValueAPF();
7019       APFloat Recip(N1APF.getSemantics(), 1); // 1.0
7020       APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
7021       // Only do the transform if the reciprocal is a legal fp immediate that
7022       // isn't too nasty (eg NaN, denormal, ...).
7023       if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
7024           (!LegalOperations ||
7025            // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
7026            // backend)... we should handle this gracefully after Legalize.
7027            // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
7028            TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
7029            TLI.isFPImmLegal(Recip, VT)))
7030         return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
7031                            DAG.getConstantFP(Recip, VT));
7032     }
7033
7034     // If this FDIV is part of a reciprocal square root, it may be folded
7035     // into a target-specific square root estimate instruction.
7036     if (N1.getOpcode() == ISD::FSQRT) {
7037       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0))) {
7038         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7039       }
7040     } else if (N1.getOpcode() == ISD::FP_EXTEND &&
7041                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
7042       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
7043         RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
7044         AddToWorklist(RV.getNode());
7045         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7046       }
7047     } else if (N1.getOpcode() == ISD::FP_ROUND &&
7048                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
7049       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
7050         RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
7051         AddToWorklist(RV.getNode());
7052         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7053       }
7054     } else if (N1.getOpcode() == ISD::FMUL) {
7055       // Look through an FMUL. Even though this won't remove the FDIV directly,
7056       // it's still worthwhile to get rid of the FSQRT if possible.
7057       SDValue SqrtOp;
7058       SDValue OtherOp;
7059       if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
7060         SqrtOp = N1.getOperand(0);
7061         OtherOp = N1.getOperand(1);
7062       } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
7063         SqrtOp = N1.getOperand(1);
7064         OtherOp = N1.getOperand(0);
7065       }
7066       if (SqrtOp.getNode()) {
7067         // We found a FSQRT, so try to make this fold:
7068         // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
7069         if (SDValue RV = BuildRsqrtEstimate(SqrtOp.getOperand(0))) {
7070           RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp);
7071           AddToWorklist(RV.getNode());
7072           return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7073         }
7074       }
7075     }
7076
7077     // Fold into a reciprocal estimate and multiply instead of a real divide.
7078     if (SDValue RV = BuildReciprocalEstimate(N1)) {
7079       AddToWorklist(RV.getNode());
7080       return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7081     }
7082   }
7083
7084   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
7085   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
7086     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
7087       // Both can be negated for free, check to see if at least one is cheaper
7088       // negated.
7089       if (LHSNeg == 2 || RHSNeg == 2)
7090         return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
7091                            GetNegatedExpression(N0, DAG, LegalOperations),
7092                            GetNegatedExpression(N1, DAG, LegalOperations));
7093     }
7094   }
7095
7096   return SDValue();
7097 }
7098
7099 SDValue DAGCombiner::visitFREM(SDNode *N) {
7100   SDValue N0 = N->getOperand(0);
7101   SDValue N1 = N->getOperand(1);
7102   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7103   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7104   EVT VT = N->getValueType(0);
7105
7106   // fold (frem c1, c2) -> fmod(c1,c2)
7107   if (N0CFP && N1CFP)
7108     return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
7109
7110   return SDValue();
7111 }
7112
7113 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
7114   if (DAG.getTarget().Options.UnsafeFPMath) {
7115     // Compute this as X * (1/sqrt(X)) = X * (X ** -0.5)
7116     if (SDValue RV = BuildRsqrtEstimate(N->getOperand(0))) {
7117       EVT VT = RV.getValueType();
7118       RV = DAG.getNode(ISD::FMUL, SDLoc(N), VT, N->getOperand(0), RV);
7119       AddToWorklist(RV.getNode());
7120
7121       // Unfortunately, RV is now NaN if the input was exactly 0.
7122       // Select out this case and force the answer to 0.
7123       SDValue Zero = DAG.getConstantFP(0.0, VT);
7124       SDValue ZeroCmp =
7125         DAG.getSetCC(SDLoc(N), TLI.getSetCCResultType(*DAG.getContext(), VT),
7126                      N->getOperand(0), Zero, ISD::SETEQ);
7127       AddToWorklist(ZeroCmp.getNode());
7128       AddToWorklist(RV.getNode());
7129
7130       RV = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT,
7131                        SDLoc(N), VT, ZeroCmp, Zero, RV);
7132       return RV;
7133     }
7134   }
7135   return SDValue();
7136 }
7137
7138 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
7139   SDValue N0 = N->getOperand(0);
7140   SDValue N1 = N->getOperand(1);
7141   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7142   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7143   EVT VT = N->getValueType(0);
7144
7145   if (N0CFP && N1CFP)  // Constant fold
7146     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
7147
7148   if (N1CFP) {
7149     const APFloat& V = N1CFP->getValueAPF();
7150     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
7151     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
7152     if (!V.isNegative()) {
7153       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
7154         return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7155     } else {
7156       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
7157         return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7158                            DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
7159     }
7160   }
7161
7162   // copysign(fabs(x), y) -> copysign(x, y)
7163   // copysign(fneg(x), y) -> copysign(x, y)
7164   // copysign(copysign(x,z), y) -> copysign(x, y)
7165   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
7166       N0.getOpcode() == ISD::FCOPYSIGN)
7167     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7168                        N0.getOperand(0), N1);
7169
7170   // copysign(x, abs(y)) -> abs(x)
7171   if (N1.getOpcode() == ISD::FABS)
7172     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7173
7174   // copysign(x, copysign(y,z)) -> copysign(x, z)
7175   if (N1.getOpcode() == ISD::FCOPYSIGN)
7176     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7177                        N0, N1.getOperand(1));
7178
7179   // copysign(x, fp_extend(y)) -> copysign(x, y)
7180   // copysign(x, fp_round(y)) -> copysign(x, y)
7181   if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
7182     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7183                        N0, N1.getOperand(0));
7184
7185   return SDValue();
7186 }
7187
7188 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
7189   SDValue N0 = N->getOperand(0);
7190   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
7191   EVT VT = N->getValueType(0);
7192   EVT OpVT = N0.getValueType();
7193
7194   // fold (sint_to_fp c1) -> c1fp
7195   if (N0C &&
7196       // ...but only if the target supports immediate floating-point values
7197       (!LegalOperations ||
7198        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7199     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7200
7201   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
7202   // but UINT_TO_FP is legal on this target, try to convert.
7203   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
7204       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
7205     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
7206     if (DAG.SignBitIsZero(N0))
7207       return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7208   }
7209
7210   // The next optimizations are desirable only if SELECT_CC can be lowered.
7211   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
7212     // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7213     if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
7214         !VT.isVector() &&
7215         (!LegalOperations ||
7216          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7217       SDValue Ops[] =
7218         { N0.getOperand(0), N0.getOperand(1),
7219           DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
7220           N0.getOperand(2) };
7221       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7222     }
7223
7224     // fold (sint_to_fp (zext (setcc x, y, cc))) ->
7225     //      (select_cc x, y, 1.0, 0.0,, cc)
7226     if (N0.getOpcode() == ISD::ZERO_EXTEND &&
7227         N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
7228         (!LegalOperations ||
7229          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7230       SDValue Ops[] =
7231         { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
7232           DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
7233           N0.getOperand(0).getOperand(2) };
7234       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7235     }
7236   }
7237
7238   return SDValue();
7239 }
7240
7241 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
7242   SDValue N0 = N->getOperand(0);
7243   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
7244   EVT VT = N->getValueType(0);
7245   EVT OpVT = N0.getValueType();
7246
7247   // fold (uint_to_fp c1) -> c1fp
7248   if (N0C &&
7249       // ...but only if the target supports immediate floating-point values
7250       (!LegalOperations ||
7251        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7252     return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7253
7254   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
7255   // but SINT_TO_FP is legal on this target, try to convert.
7256   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
7257       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
7258     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
7259     if (DAG.SignBitIsZero(N0))
7260       return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7261   }
7262
7263   // The next optimizations are desirable only if SELECT_CC can be lowered.
7264   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
7265     // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7266
7267     if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
7268         (!LegalOperations ||
7269          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7270       SDValue Ops[] =
7271         { N0.getOperand(0), N0.getOperand(1),
7272           DAG.getConstantFP(1.0, VT),  DAG.getConstantFP(0.0, VT),
7273           N0.getOperand(2) };
7274       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7275     }
7276   }
7277
7278   return SDValue();
7279 }
7280
7281 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
7282   SDValue N0 = N->getOperand(0);
7283   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7284   EVT VT = N->getValueType(0);
7285
7286   // fold (fp_to_sint c1fp) -> c1
7287   if (N0CFP)
7288     return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
7289
7290   return SDValue();
7291 }
7292
7293 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
7294   SDValue N0 = N->getOperand(0);
7295   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7296   EVT VT = N->getValueType(0);
7297
7298   // fold (fp_to_uint c1fp) -> c1
7299   if (N0CFP)
7300     return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
7301
7302   return SDValue();
7303 }
7304
7305 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
7306   SDValue N0 = N->getOperand(0);
7307   SDValue N1 = N->getOperand(1);
7308   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7309   EVT VT = N->getValueType(0);
7310
7311   // fold (fp_round c1fp) -> c1fp
7312   if (N0CFP)
7313     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
7314
7315   // fold (fp_round (fp_extend x)) -> x
7316   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
7317     return N0.getOperand(0);
7318
7319   // fold (fp_round (fp_round x)) -> (fp_round x)
7320   if (N0.getOpcode() == ISD::FP_ROUND) {
7321     // This is a value preserving truncation if both round's are.
7322     bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
7323                    N0.getNode()->getConstantOperandVal(1) == 1;
7324     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
7325                        DAG.getIntPtrConstant(IsTrunc));
7326   }
7327
7328   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
7329   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
7330     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
7331                               N0.getOperand(0), N1);
7332     AddToWorklist(Tmp.getNode());
7333     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7334                        Tmp, N0.getOperand(1));
7335   }
7336
7337   return SDValue();
7338 }
7339
7340 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
7341   SDValue N0 = N->getOperand(0);
7342   EVT VT = N->getValueType(0);
7343   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
7344   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7345
7346   // fold (fp_round_inreg c1fp) -> c1fp
7347   if (N0CFP && isTypeLegal(EVT)) {
7348     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
7349     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
7350   }
7351
7352   return SDValue();
7353 }
7354
7355 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
7356   SDValue N0 = N->getOperand(0);
7357   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7358   EVT VT = N->getValueType(0);
7359
7360   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
7361   if (N->hasOneUse() &&
7362       N->use_begin()->getOpcode() == ISD::FP_ROUND)
7363     return SDValue();
7364
7365   // fold (fp_extend c1fp) -> c1fp
7366   if (N0CFP)
7367     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
7368
7369   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
7370   // value of X.
7371   if (N0.getOpcode() == ISD::FP_ROUND
7372       && N0.getNode()->getConstantOperandVal(1) == 1) {
7373     SDValue In = N0.getOperand(0);
7374     if (In.getValueType() == VT) return In;
7375     if (VT.bitsLT(In.getValueType()))
7376       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
7377                          In, N0.getOperand(1));
7378     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
7379   }
7380
7381   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
7382   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7383        TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType())) {
7384     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7385     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
7386                                      LN0->getChain(),
7387                                      LN0->getBasePtr(), N0.getValueType(),
7388                                      LN0->getMemOperand());
7389     CombineTo(N, ExtLoad);
7390     CombineTo(N0.getNode(),
7391               DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
7392                           N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
7393               ExtLoad.getValue(1));
7394     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7395   }
7396
7397   return SDValue();
7398 }
7399
7400 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
7401   SDValue N0 = N->getOperand(0);
7402   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7403   EVT VT = N->getValueType(0);
7404
7405   // fold (fceil c1) -> fceil(c1)
7406   if (N0CFP)
7407     return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
7408
7409   return SDValue();
7410 }
7411
7412 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
7413   SDValue N0 = N->getOperand(0);
7414   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7415   EVT VT = N->getValueType(0);
7416
7417   // fold (ftrunc c1) -> ftrunc(c1)
7418   if (N0CFP)
7419     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
7420
7421   return SDValue();
7422 }
7423
7424 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
7425   SDValue N0 = N->getOperand(0);
7426   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7427   EVT VT = N->getValueType(0);
7428
7429   // fold (ffloor c1) -> ffloor(c1)
7430   if (N0CFP)
7431     return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
7432
7433   return SDValue();
7434 }
7435
7436 // FIXME: FNEG and FABS have a lot in common; refactor.
7437 SDValue DAGCombiner::visitFNEG(SDNode *N) {
7438   SDValue N0 = N->getOperand(0);
7439   EVT VT = N->getValueType(0);
7440
7441   if (VT.isVector()) {
7442     SDValue FoldedVOp = SimplifyVUnaryOp(N);
7443     if (FoldedVOp.getNode()) return FoldedVOp;
7444   }
7445
7446   // Constant fold FNEG.
7447   if (isa<ConstantFPSDNode>(N0))
7448     return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N->getOperand(0));
7449
7450   if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
7451                          &DAG.getTarget().Options))
7452     return GetNegatedExpression(N0, DAG, LegalOperations);
7453
7454   // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
7455   // constant pool values.
7456   if (!TLI.isFNegFree(VT) &&
7457       N0.getOpcode() == ISD::BITCAST &&
7458       N0.getNode()->hasOneUse()) {
7459     SDValue Int = N0.getOperand(0);
7460     EVT IntVT = Int.getValueType();
7461     if (IntVT.isInteger() && !IntVT.isVector()) {
7462       APInt SignMask;
7463       if (N0.getValueType().isVector()) {
7464         // For a vector, get a mask such as 0x80... per scalar element
7465         // and splat it.
7466         SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
7467         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
7468       } else {
7469         // For a scalar, just generate 0x80...
7470         SignMask = APInt::getSignBit(IntVT.getSizeInBits());
7471       }
7472       Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
7473                         DAG.getConstant(SignMask, IntVT));
7474       AddToWorklist(Int.getNode());
7475       return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int);
7476     }
7477   }
7478
7479   // (fneg (fmul c, x)) -> (fmul -c, x)
7480   if (N0.getOpcode() == ISD::FMUL) {
7481     ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
7482     if (CFP1) {
7483       APFloat CVal = CFP1->getValueAPF();
7484       CVal.changeSign();
7485       if (Level >= AfterLegalizeDAG &&
7486           (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
7487            TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
7488         return DAG.getNode(
7489             ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
7490             DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)));
7491     }
7492   }
7493
7494   return SDValue();
7495 }
7496
7497 SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
7498   SDValue N0 = N->getOperand(0);
7499   SDValue N1 = N->getOperand(1);
7500   const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7501   const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7502
7503   if (N0CFP && N1CFP) {
7504     const APFloat &C0 = N0CFP->getValueAPF();
7505     const APFloat &C1 = N1CFP->getValueAPF();
7506     return DAG.getConstantFP(minnum(C0, C1), N->getValueType(0));
7507   }
7508
7509   if (N0CFP) {
7510     EVT VT = N->getValueType(0);
7511     // Canonicalize to constant on RHS.
7512     return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
7513   }
7514
7515   return SDValue();
7516 }
7517
7518 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
7519   SDValue N0 = N->getOperand(0);
7520   SDValue N1 = N->getOperand(1);
7521   const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7522   const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7523
7524   if (N0CFP && N1CFP) {
7525     const APFloat &C0 = N0CFP->getValueAPF();
7526     const APFloat &C1 = N1CFP->getValueAPF();
7527     return DAG.getConstantFP(maxnum(C0, C1), N->getValueType(0));
7528   }
7529
7530   if (N0CFP) {
7531     EVT VT = N->getValueType(0);
7532     // Canonicalize to constant on RHS.
7533     return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
7534   }
7535
7536   return SDValue();
7537 }
7538
7539 SDValue DAGCombiner::visitFABS(SDNode *N) {
7540   SDValue N0 = N->getOperand(0);
7541   EVT VT = N->getValueType(0);
7542
7543   if (VT.isVector()) {
7544     SDValue FoldedVOp = SimplifyVUnaryOp(N);
7545     if (FoldedVOp.getNode()) return FoldedVOp;
7546   }
7547
7548   // fold (fabs c1) -> fabs(c1)
7549   if (isa<ConstantFPSDNode>(N0))
7550     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7551
7552   // fold (fabs (fabs x)) -> (fabs x)
7553   if (N0.getOpcode() == ISD::FABS)
7554     return N->getOperand(0);
7555
7556   // fold (fabs (fneg x)) -> (fabs x)
7557   // fold (fabs (fcopysign x, y)) -> (fabs x)
7558   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
7559     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
7560
7561   // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
7562   // constant pool values.
7563   if (!TLI.isFAbsFree(VT) &&
7564       N0.getOpcode() == ISD::BITCAST &&
7565       N0.getNode()->hasOneUse()) {
7566     SDValue Int = N0.getOperand(0);
7567     EVT IntVT = Int.getValueType();
7568     if (IntVT.isInteger() && !IntVT.isVector()) {
7569       APInt SignMask;
7570       if (N0.getValueType().isVector()) {
7571         // For a vector, get a mask such as 0x7f... per scalar element
7572         // and splat it.
7573         SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
7574         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
7575       } else {
7576         // For a scalar, just generate 0x7f...
7577         SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
7578       }
7579       Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
7580                         DAG.getConstant(SignMask, IntVT));
7581       AddToWorklist(Int.getNode());
7582       return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int);
7583     }
7584   }
7585
7586   return SDValue();
7587 }
7588
7589 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
7590   SDValue Chain = N->getOperand(0);
7591   SDValue N1 = N->getOperand(1);
7592   SDValue N2 = N->getOperand(2);
7593
7594   // If N is a constant we could fold this into a fallthrough or unconditional
7595   // branch. However that doesn't happen very often in normal code, because
7596   // Instcombine/SimplifyCFG should have handled the available opportunities.
7597   // If we did this folding here, it would be necessary to update the
7598   // MachineBasicBlock CFG, which is awkward.
7599
7600   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
7601   // on the target.
7602   if (N1.getOpcode() == ISD::SETCC &&
7603       TLI.isOperationLegalOrCustom(ISD::BR_CC,
7604                                    N1.getOperand(0).getValueType())) {
7605     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7606                        Chain, N1.getOperand(2),
7607                        N1.getOperand(0), N1.getOperand(1), N2);
7608   }
7609
7610   if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
7611       ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
7612        (N1.getOperand(0).hasOneUse() &&
7613         N1.getOperand(0).getOpcode() == ISD::SRL))) {
7614     SDNode *Trunc = nullptr;
7615     if (N1.getOpcode() == ISD::TRUNCATE) {
7616       // Look pass the truncate.
7617       Trunc = N1.getNode();
7618       N1 = N1.getOperand(0);
7619     }
7620
7621     // Match this pattern so that we can generate simpler code:
7622     //
7623     //   %a = ...
7624     //   %b = and i32 %a, 2
7625     //   %c = srl i32 %b, 1
7626     //   brcond i32 %c ...
7627     //
7628     // into
7629     //
7630     //   %a = ...
7631     //   %b = and i32 %a, 2
7632     //   %c = setcc eq %b, 0
7633     //   brcond %c ...
7634     //
7635     // This applies only when the AND constant value has one bit set and the
7636     // SRL constant is equal to the log2 of the AND constant. The back-end is
7637     // smart enough to convert the result into a TEST/JMP sequence.
7638     SDValue Op0 = N1.getOperand(0);
7639     SDValue Op1 = N1.getOperand(1);
7640
7641     if (Op0.getOpcode() == ISD::AND &&
7642         Op1.getOpcode() == ISD::Constant) {
7643       SDValue AndOp1 = Op0.getOperand(1);
7644
7645       if (AndOp1.getOpcode() == ISD::Constant) {
7646         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
7647
7648         if (AndConst.isPowerOf2() &&
7649             cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
7650           SDValue SetCC =
7651             DAG.getSetCC(SDLoc(N),
7652                          getSetCCResultType(Op0.getValueType()),
7653                          Op0, DAG.getConstant(0, Op0.getValueType()),
7654                          ISD::SETNE);
7655
7656           SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
7657                                           MVT::Other, Chain, SetCC, N2);
7658           // Don't add the new BRCond into the worklist or else SimplifySelectCC
7659           // will convert it back to (X & C1) >> C2.
7660           CombineTo(N, NewBRCond, false);
7661           // Truncate is dead.
7662           if (Trunc)
7663             deleteAndRecombine(Trunc);
7664           // Replace the uses of SRL with SETCC
7665           WorklistRemover DeadNodes(*this);
7666           DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7667           deleteAndRecombine(N1.getNode());
7668           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7669         }
7670       }
7671     }
7672
7673     if (Trunc)
7674       // Restore N1 if the above transformation doesn't match.
7675       N1 = N->getOperand(1);
7676   }
7677
7678   // Transform br(xor(x, y)) -> br(x != y)
7679   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
7680   if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
7681     SDNode *TheXor = N1.getNode();
7682     SDValue Op0 = TheXor->getOperand(0);
7683     SDValue Op1 = TheXor->getOperand(1);
7684     if (Op0.getOpcode() == Op1.getOpcode()) {
7685       // Avoid missing important xor optimizations.
7686       SDValue Tmp = visitXOR(TheXor);
7687       if (Tmp.getNode()) {
7688         if (Tmp.getNode() != TheXor) {
7689           DEBUG(dbgs() << "\nReplacing.8 ";
7690                 TheXor->dump(&DAG);
7691                 dbgs() << "\nWith: ";
7692                 Tmp.getNode()->dump(&DAG);
7693                 dbgs() << '\n');
7694           WorklistRemover DeadNodes(*this);
7695           DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
7696           deleteAndRecombine(TheXor);
7697           return DAG.getNode(ISD::BRCOND, SDLoc(N),
7698                              MVT::Other, Chain, Tmp, N2);
7699         }
7700
7701         // visitXOR has changed XOR's operands or replaced the XOR completely,
7702         // bail out.
7703         return SDValue(N, 0);
7704       }
7705     }
7706
7707     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
7708       bool Equal = false;
7709       if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
7710         if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
7711             Op0.getOpcode() == ISD::XOR) {
7712           TheXor = Op0.getNode();
7713           Equal = true;
7714         }
7715
7716       EVT SetCCVT = N1.getValueType();
7717       if (LegalTypes)
7718         SetCCVT = getSetCCResultType(SetCCVT);
7719       SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
7720                                    SetCCVT,
7721                                    Op0, Op1,
7722                                    Equal ? ISD::SETEQ : ISD::SETNE);
7723       // Replace the uses of XOR with SETCC
7724       WorklistRemover DeadNodes(*this);
7725       DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7726       deleteAndRecombine(N1.getNode());
7727       return DAG.getNode(ISD::BRCOND, SDLoc(N),
7728                          MVT::Other, Chain, SetCC, N2);
7729     }
7730   }
7731
7732   return SDValue();
7733 }
7734
7735 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
7736 //
7737 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
7738   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
7739   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
7740
7741   // If N is a constant we could fold this into a fallthrough or unconditional
7742   // branch. However that doesn't happen very often in normal code, because
7743   // Instcombine/SimplifyCFG should have handled the available opportunities.
7744   // If we did this folding here, it would be necessary to update the
7745   // MachineBasicBlock CFG, which is awkward.
7746
7747   // Use SimplifySetCC to simplify SETCC's.
7748   SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
7749                                CondLHS, CondRHS, CC->get(), SDLoc(N),
7750                                false);
7751   if (Simp.getNode()) AddToWorklist(Simp.getNode());
7752
7753   // fold to a simpler setcc
7754   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
7755     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7756                        N->getOperand(0), Simp.getOperand(2),
7757                        Simp.getOperand(0), Simp.getOperand(1),
7758                        N->getOperand(4));
7759
7760   return SDValue();
7761 }
7762
7763 /// Return true if 'Use' is a load or a store that uses N as its base pointer
7764 /// and that N may be folded in the load / store addressing mode.
7765 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
7766                                     SelectionDAG &DAG,
7767                                     const TargetLowering &TLI) {
7768   EVT VT;
7769   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
7770     if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
7771       return false;
7772     VT = Use->getValueType(0);
7773   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
7774     if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
7775       return false;
7776     VT = ST->getValue().getValueType();
7777   } else
7778     return false;
7779
7780   TargetLowering::AddrMode AM;
7781   if (N->getOpcode() == ISD::ADD) {
7782     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7783     if (Offset)
7784       // [reg +/- imm]
7785       AM.BaseOffs = Offset->getSExtValue();
7786     else
7787       // [reg +/- reg]
7788       AM.Scale = 1;
7789   } else if (N->getOpcode() == ISD::SUB) {
7790     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7791     if (Offset)
7792       // [reg +/- imm]
7793       AM.BaseOffs = -Offset->getSExtValue();
7794     else
7795       // [reg +/- reg]
7796       AM.Scale = 1;
7797   } else
7798     return false;
7799
7800   return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
7801 }
7802
7803 /// Try turning a load/store into a pre-indexed load/store when the base
7804 /// pointer is an add or subtract and it has other uses besides the load/store.
7805 /// After the transformation, the new indexed load/store has effectively folded
7806 /// the add/subtract in and all of its other uses are redirected to the
7807 /// new load/store.
7808 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
7809   if (Level < AfterLegalizeDAG)
7810     return false;
7811
7812   bool isLoad = true;
7813   SDValue Ptr;
7814   EVT VT;
7815   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
7816     if (LD->isIndexed())
7817       return false;
7818     VT = LD->getMemoryVT();
7819     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
7820         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
7821       return false;
7822     Ptr = LD->getBasePtr();
7823   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
7824     if (ST->isIndexed())
7825       return false;
7826     VT = ST->getMemoryVT();
7827     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
7828         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
7829       return false;
7830     Ptr = ST->getBasePtr();
7831     isLoad = false;
7832   } else {
7833     return false;
7834   }
7835
7836   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
7837   // out.  There is no reason to make this a preinc/predec.
7838   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
7839       Ptr.getNode()->hasOneUse())
7840     return false;
7841
7842   // Ask the target to do addressing mode selection.
7843   SDValue BasePtr;
7844   SDValue Offset;
7845   ISD::MemIndexedMode AM = ISD::UNINDEXED;
7846   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
7847     return false;
7848
7849   // Backends without true r+i pre-indexed forms may need to pass a
7850   // constant base with a variable offset so that constant coercion
7851   // will work with the patterns in canonical form.
7852   bool Swapped = false;
7853   if (isa<ConstantSDNode>(BasePtr)) {
7854     std::swap(BasePtr, Offset);
7855     Swapped = true;
7856   }
7857
7858   // Don't create a indexed load / store with zero offset.
7859   if (isa<ConstantSDNode>(Offset) &&
7860       cast<ConstantSDNode>(Offset)->isNullValue())
7861     return false;
7862
7863   // Try turning it into a pre-indexed load / store except when:
7864   // 1) The new base ptr is a frame index.
7865   // 2) If N is a store and the new base ptr is either the same as or is a
7866   //    predecessor of the value being stored.
7867   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
7868   //    that would create a cycle.
7869   // 4) All uses are load / store ops that use it as old base ptr.
7870
7871   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
7872   // (plus the implicit offset) to a register to preinc anyway.
7873   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7874     return false;
7875
7876   // Check #2.
7877   if (!isLoad) {
7878     SDValue Val = cast<StoreSDNode>(N)->getValue();
7879     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
7880       return false;
7881   }
7882
7883   // If the offset is a constant, there may be other adds of constants that
7884   // can be folded with this one. We should do this to avoid having to keep
7885   // a copy of the original base pointer.
7886   SmallVector<SDNode *, 16> OtherUses;
7887   if (isa<ConstantSDNode>(Offset))
7888     for (SDNode *Use : BasePtr.getNode()->uses()) {
7889       if (Use == Ptr.getNode())
7890         continue;
7891
7892       if (Use->isPredecessorOf(N))
7893         continue;
7894
7895       if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
7896         OtherUses.clear();
7897         break;
7898       }
7899
7900       SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
7901       if (Op1.getNode() == BasePtr.getNode())
7902         std::swap(Op0, Op1);
7903       assert(Op0.getNode() == BasePtr.getNode() &&
7904              "Use of ADD/SUB but not an operand");
7905
7906       if (!isa<ConstantSDNode>(Op1)) {
7907         OtherUses.clear();
7908         break;
7909       }
7910
7911       // FIXME: In some cases, we can be smarter about this.
7912       if (Op1.getValueType() != Offset.getValueType()) {
7913         OtherUses.clear();
7914         break;
7915       }
7916
7917       OtherUses.push_back(Use);
7918     }
7919
7920   if (Swapped)
7921     std::swap(BasePtr, Offset);
7922
7923   // Now check for #3 and #4.
7924   bool RealUse = false;
7925
7926   // Caches for hasPredecessorHelper
7927   SmallPtrSet<const SDNode *, 32> Visited;
7928   SmallVector<const SDNode *, 16> Worklist;
7929
7930   for (SDNode *Use : Ptr.getNode()->uses()) {
7931     if (Use == N)
7932       continue;
7933     if (N->hasPredecessorHelper(Use, Visited, Worklist))
7934       return false;
7935
7936     // If Ptr may be folded in addressing mode of other use, then it's
7937     // not profitable to do this transformation.
7938     if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
7939       RealUse = true;
7940   }
7941
7942   if (!RealUse)
7943     return false;
7944
7945   SDValue Result;
7946   if (isLoad)
7947     Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7948                                 BasePtr, Offset, AM);
7949   else
7950     Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7951                                  BasePtr, Offset, AM);
7952   ++PreIndexedNodes;
7953   ++NodesCombined;
7954   DEBUG(dbgs() << "\nReplacing.4 ";
7955         N->dump(&DAG);
7956         dbgs() << "\nWith: ";
7957         Result.getNode()->dump(&DAG);
7958         dbgs() << '\n');
7959   WorklistRemover DeadNodes(*this);
7960   if (isLoad) {
7961     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7962     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7963   } else {
7964     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7965   }
7966
7967   // Finally, since the node is now dead, remove it from the graph.
7968   deleteAndRecombine(N);
7969
7970   if (Swapped)
7971     std::swap(BasePtr, Offset);
7972
7973   // Replace other uses of BasePtr that can be updated to use Ptr
7974   for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
7975     unsigned OffsetIdx = 1;
7976     if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
7977       OffsetIdx = 0;
7978     assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
7979            BasePtr.getNode() && "Expected BasePtr operand");
7980
7981     // We need to replace ptr0 in the following expression:
7982     //   x0 * offset0 + y0 * ptr0 = t0
7983     // knowing that
7984     //   x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
7985     //
7986     // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
7987     // indexed load/store and the expresion that needs to be re-written.
7988     //
7989     // Therefore, we have:
7990     //   t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
7991
7992     ConstantSDNode *CN =
7993       cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
7994     int X0, X1, Y0, Y1;
7995     APInt Offset0 = CN->getAPIntValue();
7996     APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
7997
7998     X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
7999     Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
8000     X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
8001     Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
8002
8003     unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
8004
8005     APInt CNV = Offset0;
8006     if (X0 < 0) CNV = -CNV;
8007     if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
8008     else CNV = CNV - Offset1;
8009
8010     // We can now generate the new expression.
8011     SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
8012     SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
8013
8014     SDValue NewUse = DAG.getNode(Opcode,
8015                                  SDLoc(OtherUses[i]),
8016                                  OtherUses[i]->getValueType(0), NewOp1, NewOp2);
8017     DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
8018     deleteAndRecombine(OtherUses[i]);
8019   }
8020
8021   // Replace the uses of Ptr with uses of the updated base value.
8022   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
8023   deleteAndRecombine(Ptr.getNode());
8024
8025   return true;
8026 }
8027
8028 /// Try to combine a load/store with a add/sub of the base pointer node into a
8029 /// post-indexed load/store. The transformation folded the add/subtract into the
8030 /// new indexed load/store effectively and all of its uses are redirected to the
8031 /// new load/store.
8032 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
8033   if (Level < AfterLegalizeDAG)
8034     return false;
8035
8036   bool isLoad = true;
8037   SDValue Ptr;
8038   EVT VT;
8039   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
8040     if (LD->isIndexed())
8041       return false;
8042     VT = LD->getMemoryVT();
8043     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
8044         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
8045       return false;
8046     Ptr = LD->getBasePtr();
8047   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
8048     if (ST->isIndexed())
8049       return false;
8050     VT = ST->getMemoryVT();
8051     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
8052         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
8053       return false;
8054     Ptr = ST->getBasePtr();
8055     isLoad = false;
8056   } else {
8057     return false;
8058   }
8059
8060   if (Ptr.getNode()->hasOneUse())
8061     return false;
8062
8063   for (SDNode *Op : Ptr.getNode()->uses()) {
8064     if (Op == N ||
8065         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
8066       continue;
8067
8068     SDValue BasePtr;
8069     SDValue Offset;
8070     ISD::MemIndexedMode AM = ISD::UNINDEXED;
8071     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
8072       // Don't create a indexed load / store with zero offset.
8073       if (isa<ConstantSDNode>(Offset) &&
8074           cast<ConstantSDNode>(Offset)->isNullValue())
8075         continue;
8076
8077       // Try turning it into a post-indexed load / store except when
8078       // 1) All uses are load / store ops that use it as base ptr (and
8079       //    it may be folded as addressing mmode).
8080       // 2) Op must be independent of N, i.e. Op is neither a predecessor
8081       //    nor a successor of N. Otherwise, if Op is folded that would
8082       //    create a cycle.
8083
8084       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
8085         continue;
8086
8087       // Check for #1.
8088       bool TryNext = false;
8089       for (SDNode *Use : BasePtr.getNode()->uses()) {
8090         if (Use == Ptr.getNode())
8091           continue;
8092
8093         // If all the uses are load / store addresses, then don't do the
8094         // transformation.
8095         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
8096           bool RealUse = false;
8097           for (SDNode *UseUse : Use->uses()) {
8098             if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
8099               RealUse = true;
8100           }
8101
8102           if (!RealUse) {
8103             TryNext = true;
8104             break;
8105           }
8106         }
8107       }
8108
8109       if (TryNext)
8110         continue;
8111
8112       // Check for #2
8113       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
8114         SDValue Result = isLoad
8115           ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
8116                                BasePtr, Offset, AM)
8117           : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
8118                                 BasePtr, Offset, AM);
8119         ++PostIndexedNodes;
8120         ++NodesCombined;
8121         DEBUG(dbgs() << "\nReplacing.5 ";
8122               N->dump(&DAG);
8123               dbgs() << "\nWith: ";
8124               Result.getNode()->dump(&DAG);
8125               dbgs() << '\n');
8126         WorklistRemover DeadNodes(*this);
8127         if (isLoad) {
8128           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
8129           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
8130         } else {
8131           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
8132         }
8133
8134         // Finally, since the node is now dead, remove it from the graph.
8135         deleteAndRecombine(N);
8136
8137         // Replace the uses of Use with uses of the updated base value.
8138         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
8139                                       Result.getValue(isLoad ? 1 : 0));
8140         deleteAndRecombine(Op);
8141         return true;
8142       }
8143     }
8144   }
8145
8146   return false;
8147 }
8148
8149 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
8150 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
8151   ISD::MemIndexedMode AM = LD->getAddressingMode();
8152   assert(AM != ISD::UNINDEXED);
8153   SDValue BP = LD->getOperand(1);
8154   SDValue Inc = LD->getOperand(2);
8155
8156   // Some backends use TargetConstants for load offsets, but don't expect
8157   // TargetConstants in general ADD nodes. We can convert these constants into
8158   // regular Constants (if the constant is not opaque).
8159   assert((Inc.getOpcode() != ISD::TargetConstant ||
8160           !cast<ConstantSDNode>(Inc)->isOpaque()) &&
8161          "Cannot split out indexing using opaque target constants");
8162   if (Inc.getOpcode() == ISD::TargetConstant) {
8163     ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
8164     Inc = DAG.getConstant(*ConstInc->getConstantIntValue(),
8165                           ConstInc->getValueType(0));
8166   }
8167
8168   unsigned Opc =
8169       (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
8170   return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
8171 }
8172
8173 SDValue DAGCombiner::visitLOAD(SDNode *N) {
8174   LoadSDNode *LD  = cast<LoadSDNode>(N);
8175   SDValue Chain = LD->getChain();
8176   SDValue Ptr   = LD->getBasePtr();
8177
8178   // If load is not volatile and there are no uses of the loaded value (and
8179   // the updated indexed value in case of indexed loads), change uses of the
8180   // chain value into uses of the chain input (i.e. delete the dead load).
8181   if (!LD->isVolatile()) {
8182     if (N->getValueType(1) == MVT::Other) {
8183       // Unindexed loads.
8184       if (!N->hasAnyUseOfValue(0)) {
8185         // It's not safe to use the two value CombineTo variant here. e.g.
8186         // v1, chain2 = load chain1, loc
8187         // v2, chain3 = load chain2, loc
8188         // v3         = add v2, c
8189         // Now we replace use of chain2 with chain1.  This makes the second load
8190         // isomorphic to the one we are deleting, and thus makes this load live.
8191         DEBUG(dbgs() << "\nReplacing.6 ";
8192               N->dump(&DAG);
8193               dbgs() << "\nWith chain: ";
8194               Chain.getNode()->dump(&DAG);
8195               dbgs() << "\n");
8196         WorklistRemover DeadNodes(*this);
8197         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8198
8199         if (N->use_empty())
8200           deleteAndRecombine(N);
8201
8202         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8203       }
8204     } else {
8205       // Indexed loads.
8206       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
8207
8208       // If this load has an opaque TargetConstant offset, then we cannot split
8209       // the indexing into an add/sub directly (that TargetConstant may not be
8210       // valid for a different type of node, and we cannot convert an opaque
8211       // target constant into a regular constant).
8212       bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
8213                        cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
8214
8215       if (!N->hasAnyUseOfValue(0) &&
8216           ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
8217         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
8218         SDValue Index;
8219         if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
8220           Index = SplitIndexingFromLoad(LD);
8221           // Try to fold the base pointer arithmetic into subsequent loads and
8222           // stores.
8223           AddUsersToWorklist(N);
8224         } else
8225           Index = DAG.getUNDEF(N->getValueType(1));
8226         DEBUG(dbgs() << "\nReplacing.7 ";
8227               N->dump(&DAG);
8228               dbgs() << "\nWith: ";
8229               Undef.getNode()->dump(&DAG);
8230               dbgs() << " and 2 other values\n");
8231         WorklistRemover DeadNodes(*this);
8232         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
8233         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
8234         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
8235         deleteAndRecombine(N);
8236         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8237       }
8238     }
8239   }
8240
8241   // If this load is directly stored, replace the load value with the stored
8242   // value.
8243   // TODO: Handle store large -> read small portion.
8244   // TODO: Handle TRUNCSTORE/LOADEXT
8245   if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
8246     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
8247       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
8248       if (PrevST->getBasePtr() == Ptr &&
8249           PrevST->getValue().getValueType() == N->getValueType(0))
8250       return CombineTo(N, Chain.getOperand(1), Chain);
8251     }
8252   }
8253
8254   // Try to infer better alignment information than the load already has.
8255   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
8256     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
8257       if (Align > LD->getMemOperand()->getBaseAlignment()) {
8258         SDValue NewLoad =
8259                DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
8260                               LD->getValueType(0),
8261                               Chain, Ptr, LD->getPointerInfo(),
8262                               LD->getMemoryVT(),
8263                               LD->isVolatile(), LD->isNonTemporal(),
8264                               LD->isInvariant(), Align, LD->getAAInfo());
8265         return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
8266       }
8267     }
8268   }
8269
8270   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
8271                                                   : DAG.getSubtarget().useAA();
8272 #ifndef NDEBUG
8273   if (CombinerAAOnlyFunc.getNumOccurrences() &&
8274       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
8275     UseAA = false;
8276 #endif
8277   if (UseAA && LD->isUnindexed()) {
8278     // Walk up chain skipping non-aliasing memory nodes.
8279     SDValue BetterChain = FindBetterChain(N, Chain);
8280
8281     // If there is a better chain.
8282     if (Chain != BetterChain) {
8283       SDValue ReplLoad;
8284
8285       // Replace the chain to void dependency.
8286       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
8287         ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
8288                                BetterChain, Ptr, LD->getMemOperand());
8289       } else {
8290         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
8291                                   LD->getValueType(0),
8292                                   BetterChain, Ptr, LD->getMemoryVT(),
8293                                   LD->getMemOperand());
8294       }
8295
8296       // Create token factor to keep old chain connected.
8297       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
8298                                   MVT::Other, Chain, ReplLoad.getValue(1));
8299
8300       // Make sure the new and old chains are cleaned up.
8301       AddToWorklist(Token.getNode());
8302
8303       // Replace uses with load result and token factor. Don't add users
8304       // to work list.
8305       return CombineTo(N, ReplLoad.getValue(0), Token, false);
8306     }
8307   }
8308
8309   // Try transforming N to an indexed load.
8310   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
8311     return SDValue(N, 0);
8312
8313   // Try to slice up N to more direct loads if the slices are mapped to
8314   // different register banks or pairing can take place.
8315   if (SliceUpLoad(N))
8316     return SDValue(N, 0);
8317
8318   return SDValue();
8319 }
8320
8321 namespace {
8322 /// \brief Helper structure used to slice a load in smaller loads.
8323 /// Basically a slice is obtained from the following sequence:
8324 /// Origin = load Ty1, Base
8325 /// Shift = srl Ty1 Origin, CstTy Amount
8326 /// Inst = trunc Shift to Ty2
8327 ///
8328 /// Then, it will be rewriten into:
8329 /// Slice = load SliceTy, Base + SliceOffset
8330 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
8331 ///
8332 /// SliceTy is deduced from the number of bits that are actually used to
8333 /// build Inst.
8334 struct LoadedSlice {
8335   /// \brief Helper structure used to compute the cost of a slice.
8336   struct Cost {
8337     /// Are we optimizing for code size.
8338     bool ForCodeSize;
8339     /// Various cost.
8340     unsigned Loads;
8341     unsigned Truncates;
8342     unsigned CrossRegisterBanksCopies;
8343     unsigned ZExts;
8344     unsigned Shift;
8345
8346     Cost(bool ForCodeSize = false)
8347         : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
8348           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
8349
8350     /// \brief Get the cost of one isolated slice.
8351     Cost(const LoadedSlice &LS, bool ForCodeSize = false)
8352         : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
8353           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
8354       EVT TruncType = LS.Inst->getValueType(0);
8355       EVT LoadedType = LS.getLoadedType();
8356       if (TruncType != LoadedType &&
8357           !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
8358         ZExts = 1;
8359     }
8360
8361     /// \brief Account for slicing gain in the current cost.
8362     /// Slicing provide a few gains like removing a shift or a
8363     /// truncate. This method allows to grow the cost of the original
8364     /// load with the gain from this slice.
8365     void addSliceGain(const LoadedSlice &LS) {
8366       // Each slice saves a truncate.
8367       const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
8368       if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
8369                               LS.Inst->getOperand(0).getValueType()))
8370         ++Truncates;
8371       // If there is a shift amount, this slice gets rid of it.
8372       if (LS.Shift)
8373         ++Shift;
8374       // If this slice can merge a cross register bank copy, account for it.
8375       if (LS.canMergeExpensiveCrossRegisterBankCopy())
8376         ++CrossRegisterBanksCopies;
8377     }
8378
8379     Cost &operator+=(const Cost &RHS) {
8380       Loads += RHS.Loads;
8381       Truncates += RHS.Truncates;
8382       CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
8383       ZExts += RHS.ZExts;
8384       Shift += RHS.Shift;
8385       return *this;
8386     }
8387
8388     bool operator==(const Cost &RHS) const {
8389       return Loads == RHS.Loads && Truncates == RHS.Truncates &&
8390              CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
8391              ZExts == RHS.ZExts && Shift == RHS.Shift;
8392     }
8393
8394     bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
8395
8396     bool operator<(const Cost &RHS) const {
8397       // Assume cross register banks copies are as expensive as loads.
8398       // FIXME: Do we want some more target hooks?
8399       unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
8400       unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
8401       // Unless we are optimizing for code size, consider the
8402       // expensive operation first.
8403       if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
8404         return ExpensiveOpsLHS < ExpensiveOpsRHS;
8405       return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
8406              (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
8407     }
8408
8409     bool operator>(const Cost &RHS) const { return RHS < *this; }
8410
8411     bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
8412
8413     bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
8414   };
8415   // The last instruction that represent the slice. This should be a
8416   // truncate instruction.
8417   SDNode *Inst;
8418   // The original load instruction.
8419   LoadSDNode *Origin;
8420   // The right shift amount in bits from the original load.
8421   unsigned Shift;
8422   // The DAG from which Origin came from.
8423   // This is used to get some contextual information about legal types, etc.
8424   SelectionDAG *DAG;
8425
8426   LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
8427               unsigned Shift = 0, SelectionDAG *DAG = nullptr)
8428       : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
8429
8430   LoadedSlice(const LoadedSlice &LS)
8431       : Inst(LS.Inst), Origin(LS.Origin), Shift(LS.Shift), DAG(LS.DAG) {}
8432
8433   /// \brief Get the bits used in a chunk of bits \p BitWidth large.
8434   /// \return Result is \p BitWidth and has used bits set to 1 and
8435   ///         not used bits set to 0.
8436   APInt getUsedBits() const {
8437     // Reproduce the trunc(lshr) sequence:
8438     // - Start from the truncated value.
8439     // - Zero extend to the desired bit width.
8440     // - Shift left.
8441     assert(Origin && "No original load to compare against.");
8442     unsigned BitWidth = Origin->getValueSizeInBits(0);
8443     assert(Inst && "This slice is not bound to an instruction");
8444     assert(Inst->getValueSizeInBits(0) <= BitWidth &&
8445            "Extracted slice is bigger than the whole type!");
8446     APInt UsedBits(Inst->getValueSizeInBits(0), 0);
8447     UsedBits.setAllBits();
8448     UsedBits = UsedBits.zext(BitWidth);
8449     UsedBits <<= Shift;
8450     return UsedBits;
8451   }
8452
8453   /// \brief Get the size of the slice to be loaded in bytes.
8454   unsigned getLoadedSize() const {
8455     unsigned SliceSize = getUsedBits().countPopulation();
8456     assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
8457     return SliceSize / 8;
8458   }
8459
8460   /// \brief Get the type that will be loaded for this slice.
8461   /// Note: This may not be the final type for the slice.
8462   EVT getLoadedType() const {
8463     assert(DAG && "Missing context");
8464     LLVMContext &Ctxt = *DAG->getContext();
8465     return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
8466   }
8467
8468   /// \brief Get the alignment of the load used for this slice.
8469   unsigned getAlignment() const {
8470     unsigned Alignment = Origin->getAlignment();
8471     unsigned Offset = getOffsetFromBase();
8472     if (Offset != 0)
8473       Alignment = MinAlign(Alignment, Alignment + Offset);
8474     return Alignment;
8475   }
8476
8477   /// \brief Check if this slice can be rewritten with legal operations.
8478   bool isLegal() const {
8479     // An invalid slice is not legal.
8480     if (!Origin || !Inst || !DAG)
8481       return false;
8482
8483     // Offsets are for indexed load only, we do not handle that.
8484     if (Origin->getOffset().getOpcode() != ISD::UNDEF)
8485       return false;
8486
8487     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8488
8489     // Check that the type is legal.
8490     EVT SliceType = getLoadedType();
8491     if (!TLI.isTypeLegal(SliceType))
8492       return false;
8493
8494     // Check that the load is legal for this type.
8495     if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
8496       return false;
8497
8498     // Check that the offset can be computed.
8499     // 1. Check its type.
8500     EVT PtrType = Origin->getBasePtr().getValueType();
8501     if (PtrType == MVT::Untyped || PtrType.isExtended())
8502       return false;
8503
8504     // 2. Check that it fits in the immediate.
8505     if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
8506       return false;
8507
8508     // 3. Check that the computation is legal.
8509     if (!TLI.isOperationLegal(ISD::ADD, PtrType))
8510       return false;
8511
8512     // Check that the zext is legal if it needs one.
8513     EVT TruncateType = Inst->getValueType(0);
8514     if (TruncateType != SliceType &&
8515         !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
8516       return false;
8517
8518     return true;
8519   }
8520
8521   /// \brief Get the offset in bytes of this slice in the original chunk of
8522   /// bits.
8523   /// \pre DAG != nullptr.
8524   uint64_t getOffsetFromBase() const {
8525     assert(DAG && "Missing context.");
8526     bool IsBigEndian =
8527         DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
8528     assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
8529     uint64_t Offset = Shift / 8;
8530     unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
8531     assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
8532            "The size of the original loaded type is not a multiple of a"
8533            " byte.");
8534     // If Offset is bigger than TySizeInBytes, it means we are loading all
8535     // zeros. This should have been optimized before in the process.
8536     assert(TySizeInBytes > Offset &&
8537            "Invalid shift amount for given loaded size");
8538     if (IsBigEndian)
8539       Offset = TySizeInBytes - Offset - getLoadedSize();
8540     return Offset;
8541   }
8542
8543   /// \brief Generate the sequence of instructions to load the slice
8544   /// represented by this object and redirect the uses of this slice to
8545   /// this new sequence of instructions.
8546   /// \pre this->Inst && this->Origin are valid Instructions and this
8547   /// object passed the legal check: LoadedSlice::isLegal returned true.
8548   /// \return The last instruction of the sequence used to load the slice.
8549   SDValue loadSlice() const {
8550     assert(Inst && Origin && "Unable to replace a non-existing slice.");
8551     const SDValue &OldBaseAddr = Origin->getBasePtr();
8552     SDValue BaseAddr = OldBaseAddr;
8553     // Get the offset in that chunk of bytes w.r.t. the endianess.
8554     int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
8555     assert(Offset >= 0 && "Offset too big to fit in int64_t!");
8556     if (Offset) {
8557       // BaseAddr = BaseAddr + Offset.
8558       EVT ArithType = BaseAddr.getValueType();
8559       BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
8560                               DAG->getConstant(Offset, ArithType));
8561     }
8562
8563     // Create the type of the loaded slice according to its size.
8564     EVT SliceType = getLoadedType();
8565
8566     // Create the load for the slice.
8567     SDValue LastInst = DAG->getLoad(
8568         SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
8569         Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
8570         Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
8571     // If the final type is not the same as the loaded type, this means that
8572     // we have to pad with zero. Create a zero extend for that.
8573     EVT FinalType = Inst->getValueType(0);
8574     if (SliceType != FinalType)
8575       LastInst =
8576           DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
8577     return LastInst;
8578   }
8579
8580   /// \brief Check if this slice can be merged with an expensive cross register
8581   /// bank copy. E.g.,
8582   /// i = load i32
8583   /// f = bitcast i32 i to float
8584   bool canMergeExpensiveCrossRegisterBankCopy() const {
8585     if (!Inst || !Inst->hasOneUse())
8586       return false;
8587     SDNode *Use = *Inst->use_begin();
8588     if (Use->getOpcode() != ISD::BITCAST)
8589       return false;
8590     assert(DAG && "Missing context");
8591     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8592     EVT ResVT = Use->getValueType(0);
8593     const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
8594     const TargetRegisterClass *ArgRC =
8595         TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
8596     if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
8597       return false;
8598
8599     // At this point, we know that we perform a cross-register-bank copy.
8600     // Check if it is expensive.
8601     const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
8602     // Assume bitcasts are cheap, unless both register classes do not
8603     // explicitly share a common sub class.
8604     if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
8605       return false;
8606
8607     // Check if it will be merged with the load.
8608     // 1. Check the alignment constraint.
8609     unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
8610         ResVT.getTypeForEVT(*DAG->getContext()));
8611
8612     if (RequiredAlignment > getAlignment())
8613       return false;
8614
8615     // 2. Check that the load is a legal operation for that type.
8616     if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
8617       return false;
8618
8619     // 3. Check that we do not have a zext in the way.
8620     if (Inst->getValueType(0) != getLoadedType())
8621       return false;
8622
8623     return true;
8624   }
8625 };
8626 }
8627
8628 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
8629 /// \p UsedBits looks like 0..0 1..1 0..0.
8630 static bool areUsedBitsDense(const APInt &UsedBits) {
8631   // If all the bits are one, this is dense!
8632   if (UsedBits.isAllOnesValue())
8633     return true;
8634
8635   // Get rid of the unused bits on the right.
8636   APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
8637   // Get rid of the unused bits on the left.
8638   if (NarrowedUsedBits.countLeadingZeros())
8639     NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
8640   // Check that the chunk of bits is completely used.
8641   return NarrowedUsedBits.isAllOnesValue();
8642 }
8643
8644 /// \brief Check whether or not \p First and \p Second are next to each other
8645 /// in memory. This means that there is no hole between the bits loaded
8646 /// by \p First and the bits loaded by \p Second.
8647 static bool areSlicesNextToEachOther(const LoadedSlice &First,
8648                                      const LoadedSlice &Second) {
8649   assert(First.Origin == Second.Origin && First.Origin &&
8650          "Unable to match different memory origins.");
8651   APInt UsedBits = First.getUsedBits();
8652   assert((UsedBits & Second.getUsedBits()) == 0 &&
8653          "Slices are not supposed to overlap.");
8654   UsedBits |= Second.getUsedBits();
8655   return areUsedBitsDense(UsedBits);
8656 }
8657
8658 /// \brief Adjust the \p GlobalLSCost according to the target
8659 /// paring capabilities and the layout of the slices.
8660 /// \pre \p GlobalLSCost should account for at least as many loads as
8661 /// there is in the slices in \p LoadedSlices.
8662 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8663                                  LoadedSlice::Cost &GlobalLSCost) {
8664   unsigned NumberOfSlices = LoadedSlices.size();
8665   // If there is less than 2 elements, no pairing is possible.
8666   if (NumberOfSlices < 2)
8667     return;
8668
8669   // Sort the slices so that elements that are likely to be next to each
8670   // other in memory are next to each other in the list.
8671   std::sort(LoadedSlices.begin(), LoadedSlices.end(),
8672             [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
8673     assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
8674     return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
8675   });
8676   const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
8677   // First (resp. Second) is the first (resp. Second) potentially candidate
8678   // to be placed in a paired load.
8679   const LoadedSlice *First = nullptr;
8680   const LoadedSlice *Second = nullptr;
8681   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
8682                 // Set the beginning of the pair.
8683                                                            First = Second) {
8684
8685     Second = &LoadedSlices[CurrSlice];
8686
8687     // If First is NULL, it means we start a new pair.
8688     // Get to the next slice.
8689     if (!First)
8690       continue;
8691
8692     EVT LoadedType = First->getLoadedType();
8693
8694     // If the types of the slices are different, we cannot pair them.
8695     if (LoadedType != Second->getLoadedType())
8696       continue;
8697
8698     // Check if the target supplies paired loads for this type.
8699     unsigned RequiredAlignment = 0;
8700     if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
8701       // move to the next pair, this type is hopeless.
8702       Second = nullptr;
8703       continue;
8704     }
8705     // Check if we meet the alignment requirement.
8706     if (RequiredAlignment > First->getAlignment())
8707       continue;
8708
8709     // Check that both loads are next to each other in memory.
8710     if (!areSlicesNextToEachOther(*First, *Second))
8711       continue;
8712
8713     assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
8714     --GlobalLSCost.Loads;
8715     // Move to the next pair.
8716     Second = nullptr;
8717   }
8718 }
8719
8720 /// \brief Check the profitability of all involved LoadedSlice.
8721 /// Currently, it is considered profitable if there is exactly two
8722 /// involved slices (1) which are (2) next to each other in memory, and
8723 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
8724 ///
8725 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
8726 /// the elements themselves.
8727 ///
8728 /// FIXME: When the cost model will be mature enough, we can relax
8729 /// constraints (1) and (2).
8730 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8731                                 const APInt &UsedBits, bool ForCodeSize) {
8732   unsigned NumberOfSlices = LoadedSlices.size();
8733   if (StressLoadSlicing)
8734     return NumberOfSlices > 1;
8735
8736   // Check (1).
8737   if (NumberOfSlices != 2)
8738     return false;
8739
8740   // Check (2).
8741   if (!areUsedBitsDense(UsedBits))
8742     return false;
8743
8744   // Check (3).
8745   LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
8746   // The original code has one big load.
8747   OrigCost.Loads = 1;
8748   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
8749     const LoadedSlice &LS = LoadedSlices[CurrSlice];
8750     // Accumulate the cost of all the slices.
8751     LoadedSlice::Cost SliceCost(LS, ForCodeSize);
8752     GlobalSlicingCost += SliceCost;
8753
8754     // Account as cost in the original configuration the gain obtained
8755     // with the current slices.
8756     OrigCost.addSliceGain(LS);
8757   }
8758
8759   // If the target supports paired load, adjust the cost accordingly.
8760   adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
8761   return OrigCost > GlobalSlicingCost;
8762 }
8763
8764 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
8765 /// operations, split it in the various pieces being extracted.
8766 ///
8767 /// This sort of thing is introduced by SROA.
8768 /// This slicing takes care not to insert overlapping loads.
8769 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
8770 bool DAGCombiner::SliceUpLoad(SDNode *N) {
8771   if (Level < AfterLegalizeDAG)
8772     return false;
8773
8774   LoadSDNode *LD = cast<LoadSDNode>(N);
8775   if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
8776       !LD->getValueType(0).isInteger())
8777     return false;
8778
8779   // Keep track of already used bits to detect overlapping values.
8780   // In that case, we will just abort the transformation.
8781   APInt UsedBits(LD->getValueSizeInBits(0), 0);
8782
8783   SmallVector<LoadedSlice, 4> LoadedSlices;
8784
8785   // Check if this load is used as several smaller chunks of bits.
8786   // Basically, look for uses in trunc or trunc(lshr) and record a new chain
8787   // of computation for each trunc.
8788   for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
8789        UI != UIEnd; ++UI) {
8790     // Skip the uses of the chain.
8791     if (UI.getUse().getResNo() != 0)
8792       continue;
8793
8794     SDNode *User = *UI;
8795     unsigned Shift = 0;
8796
8797     // Check if this is a trunc(lshr).
8798     if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
8799         isa<ConstantSDNode>(User->getOperand(1))) {
8800       Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
8801       User = *User->use_begin();
8802     }
8803
8804     // At this point, User is a Truncate, iff we encountered, trunc or
8805     // trunc(lshr).
8806     if (User->getOpcode() != ISD::TRUNCATE)
8807       return false;
8808
8809     // The width of the type must be a power of 2 and greater than 8-bits.
8810     // Otherwise the load cannot be represented in LLVM IR.
8811     // Moreover, if we shifted with a non-8-bits multiple, the slice
8812     // will be across several bytes. We do not support that.
8813     unsigned Width = User->getValueSizeInBits(0);
8814     if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
8815       return 0;
8816
8817     // Build the slice for this chain of computations.
8818     LoadedSlice LS(User, LD, Shift, &DAG);
8819     APInt CurrentUsedBits = LS.getUsedBits();
8820
8821     // Check if this slice overlaps with another.
8822     if ((CurrentUsedBits & UsedBits) != 0)
8823       return false;
8824     // Update the bits used globally.
8825     UsedBits |= CurrentUsedBits;
8826
8827     // Check if the new slice would be legal.
8828     if (!LS.isLegal())
8829       return false;
8830
8831     // Record the slice.
8832     LoadedSlices.push_back(LS);
8833   }
8834
8835   // Abort slicing if it does not seem to be profitable.
8836   if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
8837     return false;
8838
8839   ++SlicedLoads;
8840
8841   // Rewrite each chain to use an independent load.
8842   // By construction, each chain can be represented by a unique load.
8843
8844   // Prepare the argument for the new token factor for all the slices.
8845   SmallVector<SDValue, 8> ArgChains;
8846   for (SmallVectorImpl<LoadedSlice>::const_iterator
8847            LSIt = LoadedSlices.begin(),
8848            LSItEnd = LoadedSlices.end();
8849        LSIt != LSItEnd; ++LSIt) {
8850     SDValue SliceInst = LSIt->loadSlice();
8851     CombineTo(LSIt->Inst, SliceInst, true);
8852     if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
8853       SliceInst = SliceInst.getOperand(0);
8854     assert(SliceInst->getOpcode() == ISD::LOAD &&
8855            "It takes more than a zext to get to the loaded slice!!");
8856     ArgChains.push_back(SliceInst.getValue(1));
8857   }
8858
8859   SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
8860                               ArgChains);
8861   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8862   return true;
8863 }
8864
8865 /// Check to see if V is (and load (ptr), imm), where the load is having
8866 /// specific bytes cleared out.  If so, return the byte size being masked out
8867 /// and the shift amount.
8868 static std::pair<unsigned, unsigned>
8869 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
8870   std::pair<unsigned, unsigned> Result(0, 0);
8871
8872   // Check for the structure we're looking for.
8873   if (V->getOpcode() != ISD::AND ||
8874       !isa<ConstantSDNode>(V->getOperand(1)) ||
8875       !ISD::isNormalLoad(V->getOperand(0).getNode()))
8876     return Result;
8877
8878   // Check the chain and pointer.
8879   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
8880   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
8881
8882   // The store should be chained directly to the load or be an operand of a
8883   // tokenfactor.
8884   if (LD == Chain.getNode())
8885     ; // ok.
8886   else if (Chain->getOpcode() != ISD::TokenFactor)
8887     return Result; // Fail.
8888   else {
8889     bool isOk = false;
8890     for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
8891       if (Chain->getOperand(i).getNode() == LD) {
8892         isOk = true;
8893         break;
8894       }
8895     if (!isOk) return Result;
8896   }
8897
8898   // This only handles simple types.
8899   if (V.getValueType() != MVT::i16 &&
8900       V.getValueType() != MVT::i32 &&
8901       V.getValueType() != MVT::i64)
8902     return Result;
8903
8904   // Check the constant mask.  Invert it so that the bits being masked out are
8905   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
8906   // follow the sign bit for uniformity.
8907   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
8908   unsigned NotMaskLZ = countLeadingZeros(NotMask);
8909   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
8910   unsigned NotMaskTZ = countTrailingZeros(NotMask);
8911   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
8912   if (NotMaskLZ == 64) return Result;  // All zero mask.
8913
8914   // See if we have a continuous run of bits.  If so, we have 0*1+0*
8915   if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
8916     return Result;
8917
8918   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
8919   if (V.getValueType() != MVT::i64 && NotMaskLZ)
8920     NotMaskLZ -= 64-V.getValueSizeInBits();
8921
8922   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
8923   switch (MaskedBytes) {
8924   case 1:
8925   case 2:
8926   case 4: break;
8927   default: return Result; // All one mask, or 5-byte mask.
8928   }
8929
8930   // Verify that the first bit starts at a multiple of mask so that the access
8931   // is aligned the same as the access width.
8932   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
8933
8934   Result.first = MaskedBytes;
8935   Result.second = NotMaskTZ/8;
8936   return Result;
8937 }
8938
8939
8940 /// Check to see if IVal is something that provides a value as specified by
8941 /// MaskInfo. If so, replace the specified store with a narrower store of
8942 /// truncated IVal.
8943 static SDNode *
8944 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
8945                                 SDValue IVal, StoreSDNode *St,
8946                                 DAGCombiner *DC) {
8947   unsigned NumBytes = MaskInfo.first;
8948   unsigned ByteShift = MaskInfo.second;
8949   SelectionDAG &DAG = DC->getDAG();
8950
8951   // Check to see if IVal is all zeros in the part being masked in by the 'or'
8952   // that uses this.  If not, this is not a replacement.
8953   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
8954                                   ByteShift*8, (ByteShift+NumBytes)*8);
8955   if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
8956
8957   // Check that it is legal on the target to do this.  It is legal if the new
8958   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
8959   // legalization.
8960   MVT VT = MVT::getIntegerVT(NumBytes*8);
8961   if (!DC->isTypeLegal(VT))
8962     return nullptr;
8963
8964   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
8965   // shifted by ByteShift and truncated down to NumBytes.
8966   if (ByteShift)
8967     IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
8968                        DAG.getConstant(ByteShift*8,
8969                                     DC->getShiftAmountTy(IVal.getValueType())));
8970
8971   // Figure out the offset for the store and the alignment of the access.
8972   unsigned StOffset;
8973   unsigned NewAlign = St->getAlignment();
8974
8975   if (DAG.getTargetLoweringInfo().isLittleEndian())
8976     StOffset = ByteShift;
8977   else
8978     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
8979
8980   SDValue Ptr = St->getBasePtr();
8981   if (StOffset) {
8982     Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
8983                       Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
8984     NewAlign = MinAlign(NewAlign, StOffset);
8985   }
8986
8987   // Truncate down to the new size.
8988   IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
8989
8990   ++OpsNarrowed;
8991   return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
8992                       St->getPointerInfo().getWithOffset(StOffset),
8993                       false, false, NewAlign).getNode();
8994 }
8995
8996
8997 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
8998 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
8999 /// narrowing the load and store if it would end up being a win for performance
9000 /// or code size.
9001 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
9002   StoreSDNode *ST  = cast<StoreSDNode>(N);
9003   if (ST->isVolatile())
9004     return SDValue();
9005
9006   SDValue Chain = ST->getChain();
9007   SDValue Value = ST->getValue();
9008   SDValue Ptr   = ST->getBasePtr();
9009   EVT VT = Value.getValueType();
9010
9011   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
9012     return SDValue();
9013
9014   unsigned Opc = Value.getOpcode();
9015
9016   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
9017   // is a byte mask indicating a consecutive number of bytes, check to see if
9018   // Y is known to provide just those bytes.  If so, we try to replace the
9019   // load + replace + store sequence with a single (narrower) store, which makes
9020   // the load dead.
9021   if (Opc == ISD::OR) {
9022     std::pair<unsigned, unsigned> MaskedLoad;
9023     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
9024     if (MaskedLoad.first)
9025       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
9026                                                   Value.getOperand(1), ST,this))
9027         return SDValue(NewST, 0);
9028
9029     // Or is commutative, so try swapping X and Y.
9030     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
9031     if (MaskedLoad.first)
9032       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
9033                                                   Value.getOperand(0), ST,this))
9034         return SDValue(NewST, 0);
9035   }
9036
9037   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
9038       Value.getOperand(1).getOpcode() != ISD::Constant)
9039     return SDValue();
9040
9041   SDValue N0 = Value.getOperand(0);
9042   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
9043       Chain == SDValue(N0.getNode(), 1)) {
9044     LoadSDNode *LD = cast<LoadSDNode>(N0);
9045     if (LD->getBasePtr() != Ptr ||
9046         LD->getPointerInfo().getAddrSpace() !=
9047         ST->getPointerInfo().getAddrSpace())
9048       return SDValue();
9049
9050     // Find the type to narrow it the load / op / store to.
9051     SDValue N1 = Value.getOperand(1);
9052     unsigned BitWidth = N1.getValueSizeInBits();
9053     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
9054     if (Opc == ISD::AND)
9055       Imm ^= APInt::getAllOnesValue(BitWidth);
9056     if (Imm == 0 || Imm.isAllOnesValue())
9057       return SDValue();
9058     unsigned ShAmt = Imm.countTrailingZeros();
9059     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
9060     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
9061     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
9062     while (NewBW < BitWidth &&
9063            !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
9064              TLI.isNarrowingProfitable(VT, NewVT))) {
9065       NewBW = NextPowerOf2(NewBW);
9066       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
9067     }
9068     if (NewBW >= BitWidth)
9069       return SDValue();
9070
9071     // If the lsb changed does not start at the type bitwidth boundary,
9072     // start at the previous one.
9073     if (ShAmt % NewBW)
9074       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
9075     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
9076                                    std::min(BitWidth, ShAmt + NewBW));
9077     if ((Imm & Mask) == Imm) {
9078       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
9079       if (Opc == ISD::AND)
9080         NewImm ^= APInt::getAllOnesValue(NewBW);
9081       uint64_t PtrOff = ShAmt / 8;
9082       // For big endian targets, we need to adjust the offset to the pointer to
9083       // load the correct bytes.
9084       if (TLI.isBigEndian())
9085         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
9086
9087       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
9088       Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
9089       if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
9090         return SDValue();
9091
9092       SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
9093                                    Ptr.getValueType(), Ptr,
9094                                    DAG.getConstant(PtrOff, Ptr.getValueType()));
9095       SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
9096                                   LD->getChain(), NewPtr,
9097                                   LD->getPointerInfo().getWithOffset(PtrOff),
9098                                   LD->isVolatile(), LD->isNonTemporal(),
9099                                   LD->isInvariant(), NewAlign,
9100                                   LD->getAAInfo());
9101       SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
9102                                    DAG.getConstant(NewImm, NewVT));
9103       SDValue NewST = DAG.getStore(Chain, SDLoc(N),
9104                                    NewVal, NewPtr,
9105                                    ST->getPointerInfo().getWithOffset(PtrOff),
9106                                    false, false, NewAlign);
9107
9108       AddToWorklist(NewPtr.getNode());
9109       AddToWorklist(NewLD.getNode());
9110       AddToWorklist(NewVal.getNode());
9111       WorklistRemover DeadNodes(*this);
9112       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
9113       ++OpsNarrowed;
9114       return NewST;
9115     }
9116   }
9117
9118   return SDValue();
9119 }
9120
9121 /// For a given floating point load / store pair, if the load value isn't used
9122 /// by any other operations, then consider transforming the pair to integer
9123 /// load / store operations if the target deems the transformation profitable.
9124 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
9125   StoreSDNode *ST  = cast<StoreSDNode>(N);
9126   SDValue Chain = ST->getChain();
9127   SDValue Value = ST->getValue();
9128   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
9129       Value.hasOneUse() &&
9130       Chain == SDValue(Value.getNode(), 1)) {
9131     LoadSDNode *LD = cast<LoadSDNode>(Value);
9132     EVT VT = LD->getMemoryVT();
9133     if (!VT.isFloatingPoint() ||
9134         VT != ST->getMemoryVT() ||
9135         LD->isNonTemporal() ||
9136         ST->isNonTemporal() ||
9137         LD->getPointerInfo().getAddrSpace() != 0 ||
9138         ST->getPointerInfo().getAddrSpace() != 0)
9139       return SDValue();
9140
9141     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
9142     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
9143         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
9144         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
9145         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
9146       return SDValue();
9147
9148     unsigned LDAlign = LD->getAlignment();
9149     unsigned STAlign = ST->getAlignment();
9150     Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
9151     unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
9152     if (LDAlign < ABIAlign || STAlign < ABIAlign)
9153       return SDValue();
9154
9155     SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
9156                                 LD->getChain(), LD->getBasePtr(),
9157                                 LD->getPointerInfo(),
9158                                 false, false, false, LDAlign);
9159
9160     SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
9161                                  NewLD, ST->getBasePtr(),
9162                                  ST->getPointerInfo(),
9163                                  false, false, STAlign);
9164
9165     AddToWorklist(NewLD.getNode());
9166     AddToWorklist(NewST.getNode());
9167     WorklistRemover DeadNodes(*this);
9168     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
9169     ++LdStFP2Int;
9170     return NewST;
9171   }
9172
9173   return SDValue();
9174 }
9175
9176 /// Helper struct to parse and store a memory address as base + index + offset.
9177 /// We ignore sign extensions when it is safe to do so.
9178 /// The following two expressions are not equivalent. To differentiate we need
9179 /// to store whether there was a sign extension involved in the index
9180 /// computation.
9181 ///  (load (i64 add (i64 copyfromreg %c)
9182 ///                 (i64 signextend (add (i8 load %index)
9183 ///                                      (i8 1))))
9184 /// vs
9185 ///
9186 /// (load (i64 add (i64 copyfromreg %c)
9187 ///                (i64 signextend (i32 add (i32 signextend (i8 load %index))
9188 ///                                         (i32 1)))))
9189 struct BaseIndexOffset {
9190   SDValue Base;
9191   SDValue Index;
9192   int64_t Offset;
9193   bool IsIndexSignExt;
9194
9195   BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
9196
9197   BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
9198                   bool IsIndexSignExt) :
9199     Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
9200
9201   bool equalBaseIndex(const BaseIndexOffset &Other) {
9202     return Other.Base == Base && Other.Index == Index &&
9203       Other.IsIndexSignExt == IsIndexSignExt;
9204   }
9205
9206   /// Parses tree in Ptr for base, index, offset addresses.
9207   static BaseIndexOffset match(SDValue Ptr) {
9208     bool IsIndexSignExt = false;
9209
9210     // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
9211     // instruction, then it could be just the BASE or everything else we don't
9212     // know how to handle. Just use Ptr as BASE and give up.
9213     if (Ptr->getOpcode() != ISD::ADD)
9214       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9215
9216     // We know that we have at least an ADD instruction. Try to pattern match
9217     // the simple case of BASE + OFFSET.
9218     if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
9219       int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
9220       return  BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
9221                               IsIndexSignExt);
9222     }
9223
9224     // Inside a loop the current BASE pointer is calculated using an ADD and a
9225     // MUL instruction. In this case Ptr is the actual BASE pointer.
9226     // (i64 add (i64 %array_ptr)
9227     //          (i64 mul (i64 %induction_var)
9228     //                   (i64 %element_size)))
9229     if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
9230       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9231
9232     // Look at Base + Index + Offset cases.
9233     SDValue Base = Ptr->getOperand(0);
9234     SDValue IndexOffset = Ptr->getOperand(1);
9235
9236     // Skip signextends.
9237     if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
9238       IndexOffset = IndexOffset->getOperand(0);
9239       IsIndexSignExt = true;
9240     }
9241
9242     // Either the case of Base + Index (no offset) or something else.
9243     if (IndexOffset->getOpcode() != ISD::ADD)
9244       return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
9245
9246     // Now we have the case of Base + Index + offset.
9247     SDValue Index = IndexOffset->getOperand(0);
9248     SDValue Offset = IndexOffset->getOperand(1);
9249
9250     if (!isa<ConstantSDNode>(Offset))
9251       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9252
9253     // Ignore signextends.
9254     if (Index->getOpcode() == ISD::SIGN_EXTEND) {
9255       Index = Index->getOperand(0);
9256       IsIndexSignExt = true;
9257     } else IsIndexSignExt = false;
9258
9259     int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
9260     return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
9261   }
9262 };
9263
9264 /// Holds a pointer to an LSBaseSDNode as well as information on where it
9265 /// is located in a sequence of memory operations connected by a chain.
9266 struct MemOpLink {
9267   MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
9268     MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
9269   // Ptr to the mem node.
9270   LSBaseSDNode *MemNode;
9271   // Offset from the base ptr.
9272   int64_t OffsetFromBase;
9273   // What is the sequence number of this mem node.
9274   // Lowest mem operand in the DAG starts at zero.
9275   unsigned SequenceNum;
9276 };
9277
9278 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
9279   EVT MemVT = St->getMemoryVT();
9280   int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
9281   bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes().
9282     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
9283
9284   // Don't merge vectors into wider inputs.
9285   if (MemVT.isVector() || !MemVT.isSimple())
9286     return false;
9287
9288   // Perform an early exit check. Do not bother looking at stored values that
9289   // are not constants or loads.
9290   SDValue StoredVal = St->getValue();
9291   bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
9292   if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) &&
9293       !IsLoadSrc)
9294     return false;
9295
9296   // Only look at ends of store sequences.
9297   SDValue Chain = SDValue(St, 0);
9298   if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
9299     return false;
9300
9301   // This holds the base pointer, index, and the offset in bytes from the base
9302   // pointer.
9303   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
9304
9305   // We must have a base and an offset.
9306   if (!BasePtr.Base.getNode())
9307     return false;
9308
9309   // Do not handle stores to undef base pointers.
9310   if (BasePtr.Base.getOpcode() == ISD::UNDEF)
9311     return false;
9312
9313   // Save the LoadSDNodes that we find in the chain.
9314   // We need to make sure that these nodes do not interfere with
9315   // any of the store nodes.
9316   SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
9317
9318   // Save the StoreSDNodes that we find in the chain.
9319   SmallVector<MemOpLink, 8> StoreNodes;
9320
9321   // Walk up the chain and look for nodes with offsets from the same
9322   // base pointer. Stop when reaching an instruction with a different kind
9323   // or instruction which has a different base pointer.
9324   unsigned Seq = 0;
9325   StoreSDNode *Index = St;
9326   while (Index) {
9327     // If the chain has more than one use, then we can't reorder the mem ops.
9328     if (Index != St && !SDValue(Index, 0)->hasOneUse())
9329       break;
9330
9331     // Find the base pointer and offset for this memory node.
9332     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
9333
9334     // Check that the base pointer is the same as the original one.
9335     if (!Ptr.equalBaseIndex(BasePtr))
9336       break;
9337
9338     // Check that the alignment is the same.
9339     if (Index->getAlignment() != St->getAlignment())
9340       break;
9341
9342     // The memory operands must not be volatile.
9343     if (Index->isVolatile() || Index->isIndexed())
9344       break;
9345
9346     // No truncation.
9347     if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
9348       if (St->isTruncatingStore())
9349         break;
9350
9351     // The stored memory type must be the same.
9352     if (Index->getMemoryVT() != MemVT)
9353       break;
9354
9355     // We do not allow unaligned stores because we want to prevent overriding
9356     // stores.
9357     if (Index->getAlignment()*8 != MemVT.getSizeInBits())
9358       break;
9359
9360     // We found a potential memory operand to merge.
9361     StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
9362
9363     // Find the next memory operand in the chain. If the next operand in the
9364     // chain is a store then move up and continue the scan with the next
9365     // memory operand. If the next operand is a load save it and use alias
9366     // information to check if it interferes with anything.
9367     SDNode *NextInChain = Index->getChain().getNode();
9368     while (1) {
9369       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
9370         // We found a store node. Use it for the next iteration.
9371         Index = STn;
9372         break;
9373       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
9374         if (Ldn->isVolatile()) {
9375           Index = nullptr;
9376           break;
9377         }
9378
9379         // Save the load node for later. Continue the scan.
9380         AliasLoadNodes.push_back(Ldn);
9381         NextInChain = Ldn->getChain().getNode();
9382         continue;
9383       } else {
9384         Index = nullptr;
9385         break;
9386       }
9387     }
9388   }
9389
9390   // Check if there is anything to merge.
9391   if (StoreNodes.size() < 2)
9392     return false;
9393
9394   // Sort the memory operands according to their distance from the base pointer.
9395   std::sort(StoreNodes.begin(), StoreNodes.end(),
9396             [](MemOpLink LHS, MemOpLink RHS) {
9397     return LHS.OffsetFromBase < RHS.OffsetFromBase ||
9398            (LHS.OffsetFromBase == RHS.OffsetFromBase &&
9399             LHS.SequenceNum > RHS.SequenceNum);
9400   });
9401
9402   // Scan the memory operations on the chain and find the first non-consecutive
9403   // store memory address.
9404   unsigned LastConsecutiveStore = 0;
9405   int64_t StartAddress = StoreNodes[0].OffsetFromBase;
9406   for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
9407
9408     // Check that the addresses are consecutive starting from the second
9409     // element in the list of stores.
9410     if (i > 0) {
9411       int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
9412       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9413         break;
9414     }
9415
9416     bool Alias = false;
9417     // Check if this store interferes with any of the loads that we found.
9418     for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
9419       if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
9420         Alias = true;
9421         break;
9422       }
9423     // We found a load that alias with this store. Stop the sequence.
9424     if (Alias)
9425       break;
9426
9427     // Mark this node as useful.
9428     LastConsecutiveStore = i;
9429   }
9430
9431   // The node with the lowest store address.
9432   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
9433
9434   // Store the constants into memory as one consecutive store.
9435   if (!IsLoadSrc) {
9436     unsigned LastLegalType = 0;
9437     unsigned LastLegalVectorType = 0;
9438     bool NonZero = false;
9439     for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9440       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
9441       SDValue StoredVal = St->getValue();
9442
9443       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
9444         NonZero |= !C->isNullValue();
9445       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
9446         NonZero |= !C->getConstantFPValue()->isNullValue();
9447       } else {
9448         // Non-constant.
9449         break;
9450       }
9451
9452       // Find a legal type for the constant store.
9453       unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9454       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9455       if (TLI.isTypeLegal(StoreTy))
9456         LastLegalType = i+1;
9457       // Or check whether a truncstore is legal.
9458       else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9459                TargetLowering::TypePromoteInteger) {
9460         EVT LegalizedStoredValueTy =
9461           TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
9462         if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
9463           LastLegalType = i+1;
9464       }
9465
9466       // Find a legal type for the vector store.
9467       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9468       if (TLI.isTypeLegal(Ty))
9469         LastLegalVectorType = i + 1;
9470     }
9471
9472     // We only use vectors if the constant is known to be zero and the
9473     // function is not marked with the noimplicitfloat attribute.
9474     if (NonZero || NoVectors)
9475       LastLegalVectorType = 0;
9476
9477     // Check if we found a legal integer type to store.
9478     if (LastLegalType == 0 && LastLegalVectorType == 0)
9479       return false;
9480
9481     bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
9482     unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
9483
9484     // Make sure we have something to merge.
9485     if (NumElem < 2)
9486       return false;
9487
9488     unsigned EarliestNodeUsed = 0;
9489     for (unsigned i=0; i < NumElem; ++i) {
9490       // Find a chain for the new wide-store operand. Notice that some
9491       // of the store nodes that we found may not be selected for inclusion
9492       // in the wide store. The chain we use needs to be the chain of the
9493       // earliest store node which is *used* and replaced by the wide store.
9494       if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9495         EarliestNodeUsed = i;
9496     }
9497
9498     // The earliest Node in the DAG.
9499     LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9500     SDLoc DL(StoreNodes[0].MemNode);
9501
9502     SDValue StoredVal;
9503     if (UseVector) {
9504       // Find a legal type for the vector store.
9505       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9506       assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
9507       StoredVal = DAG.getConstant(0, Ty);
9508     } else {
9509       unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9510       APInt StoreInt(StoreBW, 0);
9511
9512       // Construct a single integer constant which is made of the smaller
9513       // constant inputs.
9514       bool IsLE = TLI.isLittleEndian();
9515       for (unsigned i = 0; i < NumElem ; ++i) {
9516         unsigned Idx = IsLE ?(NumElem - 1 - i) : i;
9517         StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
9518         SDValue Val = St->getValue();
9519         StoreInt<<=ElementSizeBytes*8;
9520         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
9521           StoreInt|=C->getAPIntValue().zext(StoreBW);
9522         } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
9523           StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
9524         } else {
9525           assert(false && "Invalid constant element type");
9526         }
9527       }
9528
9529       // Create the new Load and Store operations.
9530       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9531       StoredVal = DAG.getConstant(StoreInt, StoreTy);
9532     }
9533
9534     SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
9535                                     FirstInChain->getBasePtr(),
9536                                     FirstInChain->getPointerInfo(),
9537                                     false, false,
9538                                     FirstInChain->getAlignment());
9539
9540     // Replace the first store with the new store
9541     CombineTo(EarliestOp, NewStore);
9542     // Erase all other stores.
9543     for (unsigned i = 0; i < NumElem ; ++i) {
9544       if (StoreNodes[i].MemNode == EarliestOp)
9545         continue;
9546       StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9547       // ReplaceAllUsesWith will replace all uses that existed when it was
9548       // called, but graph optimizations may cause new ones to appear. For
9549       // example, the case in pr14333 looks like
9550       //
9551       //  St's chain -> St -> another store -> X
9552       //
9553       // And the only difference from St to the other store is the chain.
9554       // When we change it's chain to be St's chain they become identical,
9555       // get CSEed and the net result is that X is now a use of St.
9556       // Since we know that St is redundant, just iterate.
9557       while (!St->use_empty())
9558         DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
9559       deleteAndRecombine(St);
9560     }
9561
9562     return true;
9563   }
9564
9565   // Below we handle the case of multiple consecutive stores that
9566   // come from multiple consecutive loads. We merge them into a single
9567   // wide load and a single wide store.
9568
9569   // Look for load nodes which are used by the stored values.
9570   SmallVector<MemOpLink, 8> LoadNodes;
9571
9572   // Find acceptable loads. Loads need to have the same chain (token factor),
9573   // must not be zext, volatile, indexed, and they must be consecutive.
9574   BaseIndexOffset LdBasePtr;
9575   for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9576     StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
9577     LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
9578     if (!Ld) break;
9579
9580     // Loads must only have one use.
9581     if (!Ld->hasNUsesOfValue(1, 0))
9582       break;
9583
9584     // Check that the alignment is the same as the stores.
9585     if (Ld->getAlignment() != St->getAlignment())
9586       break;
9587
9588     // The memory operands must not be volatile.
9589     if (Ld->isVolatile() || Ld->isIndexed())
9590       break;
9591
9592     // We do not accept ext loads.
9593     if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
9594       break;
9595
9596     // The stored memory type must be the same.
9597     if (Ld->getMemoryVT() != MemVT)
9598       break;
9599
9600     BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
9601     // If this is not the first ptr that we check.
9602     if (LdBasePtr.Base.getNode()) {
9603       // The base ptr must be the same.
9604       if (!LdPtr.equalBaseIndex(LdBasePtr))
9605         break;
9606     } else {
9607       // Check that all other base pointers are the same as this one.
9608       LdBasePtr = LdPtr;
9609     }
9610
9611     // We found a potential memory operand to merge.
9612     LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
9613   }
9614
9615   if (LoadNodes.size() < 2)
9616     return false;
9617
9618   // If we have load/store pair instructions and we only have two values,
9619   // don't bother.
9620   unsigned RequiredAlignment;
9621   if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
9622       St->getAlignment() >= RequiredAlignment)
9623     return false;
9624
9625   // Scan the memory operations on the chain and find the first non-consecutive
9626   // load memory address. These variables hold the index in the store node
9627   // array.
9628   unsigned LastConsecutiveLoad = 0;
9629   // This variable refers to the size and not index in the array.
9630   unsigned LastLegalVectorType = 0;
9631   unsigned LastLegalIntegerType = 0;
9632   StartAddress = LoadNodes[0].OffsetFromBase;
9633   SDValue FirstChain = LoadNodes[0].MemNode->getChain();
9634   for (unsigned i = 1; i < LoadNodes.size(); ++i) {
9635     // All loads much share the same chain.
9636     if (LoadNodes[i].MemNode->getChain() != FirstChain)
9637       break;
9638
9639     int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
9640     if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9641       break;
9642     LastConsecutiveLoad = i;
9643
9644     // Find a legal type for the vector store.
9645     EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9646     if (TLI.isTypeLegal(StoreTy))
9647       LastLegalVectorType = i + 1;
9648
9649     // Find a legal type for the integer store.
9650     unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9651     StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9652     if (TLI.isTypeLegal(StoreTy))
9653       LastLegalIntegerType = i + 1;
9654     // Or check whether a truncstore and extload is legal.
9655     else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9656              TargetLowering::TypePromoteInteger) {
9657       EVT LegalizedStoredValueTy =
9658         TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
9659       if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
9660           TLI.isLoadExtLegal(ISD::ZEXTLOAD, StoreTy) &&
9661           TLI.isLoadExtLegal(ISD::SEXTLOAD, StoreTy) &&
9662           TLI.isLoadExtLegal(ISD::EXTLOAD, StoreTy))
9663         LastLegalIntegerType = i+1;
9664     }
9665   }
9666
9667   // Only use vector types if the vector type is larger than the integer type.
9668   // If they are the same, use integers.
9669   bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
9670   unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
9671
9672   // We add +1 here because the LastXXX variables refer to location while
9673   // the NumElem refers to array/index size.
9674   unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
9675   NumElem = std::min(LastLegalType, NumElem);
9676
9677   if (NumElem < 2)
9678     return false;
9679
9680   // The earliest Node in the DAG.
9681   unsigned EarliestNodeUsed = 0;
9682   LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9683   for (unsigned i=1; i<NumElem; ++i) {
9684     // Find a chain for the new wide-store operand. Notice that some
9685     // of the store nodes that we found may not be selected for inclusion
9686     // in the wide store. The chain we use needs to be the chain of the
9687     // earliest store node which is *used* and replaced by the wide store.
9688     if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9689       EarliestNodeUsed = i;
9690   }
9691
9692   // Find if it is better to use vectors or integers to load and store
9693   // to memory.
9694   EVT JointMemOpVT;
9695   if (UseVectorTy) {
9696     JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9697   } else {
9698     unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9699     JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9700   }
9701
9702   SDLoc LoadDL(LoadNodes[0].MemNode);
9703   SDLoc StoreDL(StoreNodes[0].MemNode);
9704
9705   LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
9706   SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
9707                                 FirstLoad->getChain(),
9708                                 FirstLoad->getBasePtr(),
9709                                 FirstLoad->getPointerInfo(),
9710                                 false, false, false,
9711                                 FirstLoad->getAlignment());
9712
9713   SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
9714                                   FirstInChain->getBasePtr(),
9715                                   FirstInChain->getPointerInfo(), false, false,
9716                                   FirstInChain->getAlignment());
9717
9718   // Replace one of the loads with the new load.
9719   LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
9720   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
9721                                 SDValue(NewLoad.getNode(), 1));
9722
9723   // Remove the rest of the load chains.
9724   for (unsigned i = 1; i < NumElem ; ++i) {
9725     // Replace all chain users of the old load nodes with the chain of the new
9726     // load node.
9727     LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
9728     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
9729   }
9730
9731   // Replace the first store with the new store.
9732   CombineTo(EarliestOp, NewStore);
9733   // Erase all other stores.
9734   for (unsigned i = 0; i < NumElem ; ++i) {
9735     // Remove all Store nodes.
9736     if (StoreNodes[i].MemNode == EarliestOp)
9737       continue;
9738     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9739     DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
9740     deleteAndRecombine(St);
9741   }
9742
9743   return true;
9744 }
9745
9746 SDValue DAGCombiner::visitSTORE(SDNode *N) {
9747   StoreSDNode *ST  = cast<StoreSDNode>(N);
9748   SDValue Chain = ST->getChain();
9749   SDValue Value = ST->getValue();
9750   SDValue Ptr   = ST->getBasePtr();
9751
9752   // If this is a store of a bit convert, store the input value if the
9753   // resultant store does not need a higher alignment than the original.
9754   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
9755       ST->isUnindexed()) {
9756     unsigned OrigAlign = ST->getAlignment();
9757     EVT SVT = Value.getOperand(0).getValueType();
9758     unsigned Align = TLI.getDataLayout()->
9759       getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
9760     if (Align <= OrigAlign &&
9761         ((!LegalOperations && !ST->isVolatile()) ||
9762          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
9763       return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
9764                           Ptr, ST->getPointerInfo(), ST->isVolatile(),
9765                           ST->isNonTemporal(), OrigAlign,
9766                           ST->getAAInfo());
9767   }
9768
9769   // Turn 'store undef, Ptr' -> nothing.
9770   if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
9771     return Chain;
9772
9773   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
9774   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
9775     // NOTE: If the original store is volatile, this transform must not increase
9776     // the number of stores.  For example, on x86-32 an f64 can be stored in one
9777     // processor operation but an i64 (which is not legal) requires two.  So the
9778     // transform should not be done in this case.
9779     if (Value.getOpcode() != ISD::TargetConstantFP) {
9780       SDValue Tmp;
9781       switch (CFP->getSimpleValueType(0).SimpleTy) {
9782       default: llvm_unreachable("Unknown FP type");
9783       case MVT::f16:    // We don't do this for these yet.
9784       case MVT::f80:
9785       case MVT::f128:
9786       case MVT::ppcf128:
9787         break;
9788       case MVT::f32:
9789         if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
9790             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9791           Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
9792                               bitcastToAPInt().getZExtValue(), MVT::i32);
9793           return DAG.getStore(Chain, SDLoc(N), Tmp,
9794                               Ptr, ST->getMemOperand());
9795         }
9796         break;
9797       case MVT::f64:
9798         if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
9799              !ST->isVolatile()) ||
9800             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
9801           Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
9802                                 getZExtValue(), MVT::i64);
9803           return DAG.getStore(Chain, SDLoc(N), Tmp,
9804                               Ptr, ST->getMemOperand());
9805         }
9806
9807         if (!ST->isVolatile() &&
9808             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9809           // Many FP stores are not made apparent until after legalize, e.g. for
9810           // argument passing.  Since this is so common, custom legalize the
9811           // 64-bit integer store into two 32-bit stores.
9812           uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
9813           SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
9814           SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
9815           if (TLI.isBigEndian()) std::swap(Lo, Hi);
9816
9817           unsigned Alignment = ST->getAlignment();
9818           bool isVolatile = ST->isVolatile();
9819           bool isNonTemporal = ST->isNonTemporal();
9820           AAMDNodes AAInfo = ST->getAAInfo();
9821
9822           SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
9823                                      Ptr, ST->getPointerInfo(),
9824                                      isVolatile, isNonTemporal,
9825                                      ST->getAlignment(), AAInfo);
9826           Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
9827                             DAG.getConstant(4, Ptr.getValueType()));
9828           Alignment = MinAlign(Alignment, 4U);
9829           SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
9830                                      Ptr, ST->getPointerInfo().getWithOffset(4),
9831                                      isVolatile, isNonTemporal,
9832                                      Alignment, AAInfo);
9833           return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
9834                              St0, St1);
9835         }
9836
9837         break;
9838       }
9839     }
9840   }
9841
9842   // Try to infer better alignment information than the store already has.
9843   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
9844     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9845       if (Align > ST->getAlignment())
9846         return DAG.getTruncStore(Chain, SDLoc(N), Value,
9847                                  Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
9848                                  ST->isVolatile(), ST->isNonTemporal(), Align,
9849                                  ST->getAAInfo());
9850     }
9851   }
9852
9853   // Try transforming a pair floating point load / store ops to integer
9854   // load / store ops.
9855   SDValue NewST = TransformFPLoadStorePair(N);
9856   if (NewST.getNode())
9857     return NewST;
9858
9859   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
9860                                                   : DAG.getSubtarget().useAA();
9861 #ifndef NDEBUG
9862   if (CombinerAAOnlyFunc.getNumOccurrences() &&
9863       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9864     UseAA = false;
9865 #endif
9866   if (UseAA && ST->isUnindexed()) {
9867     // Walk up chain skipping non-aliasing memory nodes.
9868     SDValue BetterChain = FindBetterChain(N, Chain);
9869
9870     // If there is a better chain.
9871     if (Chain != BetterChain) {
9872       SDValue ReplStore;
9873
9874       // Replace the chain to avoid dependency.
9875       if (ST->isTruncatingStore()) {
9876         ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
9877                                       ST->getMemoryVT(), ST->getMemOperand());
9878       } else {
9879         ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
9880                                  ST->getMemOperand());
9881       }
9882
9883       // Create token to keep both nodes around.
9884       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9885                                   MVT::Other, Chain, ReplStore);
9886
9887       // Make sure the new and old chains are cleaned up.
9888       AddToWorklist(Token.getNode());
9889
9890       // Don't add users to work list.
9891       return CombineTo(N, Token, false);
9892     }
9893   }
9894
9895   // Try transforming N to an indexed store.
9896   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9897     return SDValue(N, 0);
9898
9899   // FIXME: is there such a thing as a truncating indexed store?
9900   if (ST->isTruncatingStore() && ST->isUnindexed() &&
9901       Value.getValueType().isInteger()) {
9902     // See if we can simplify the input to this truncstore with knowledge that
9903     // only the low bits are being used.  For example:
9904     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
9905     SDValue Shorter =
9906       GetDemandedBits(Value,
9907                       APInt::getLowBitsSet(
9908                         Value.getValueType().getScalarType().getSizeInBits(),
9909                         ST->getMemoryVT().getScalarType().getSizeInBits()));
9910     AddToWorklist(Value.getNode());
9911     if (Shorter.getNode())
9912       return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
9913                                Ptr, ST->getMemoryVT(), ST->getMemOperand());
9914
9915     // Otherwise, see if we can simplify the operation with
9916     // SimplifyDemandedBits, which only works if the value has a single use.
9917     if (SimplifyDemandedBits(Value,
9918                         APInt::getLowBitsSet(
9919                           Value.getValueType().getScalarType().getSizeInBits(),
9920                           ST->getMemoryVT().getScalarType().getSizeInBits())))
9921       return SDValue(N, 0);
9922   }
9923
9924   // If this is a load followed by a store to the same location, then the store
9925   // is dead/noop.
9926   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
9927     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
9928         ST->isUnindexed() && !ST->isVolatile() &&
9929         // There can't be any side effects between the load and store, such as
9930         // a call or store.
9931         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
9932       // The store is dead, remove it.
9933       return Chain;
9934     }
9935   }
9936
9937   // If this is a store followed by a store with the same value to the same
9938   // location, then the store is dead/noop.
9939   if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
9940     if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() &&
9941         ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() &&
9942         ST1->isUnindexed() && !ST1->isVolatile()) {
9943       // The store is dead, remove it.
9944       return Chain;
9945     }
9946   }
9947
9948   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
9949   // truncating store.  We can do this even if this is already a truncstore.
9950   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
9951       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
9952       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
9953                             ST->getMemoryVT())) {
9954     return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
9955                              Ptr, ST->getMemoryVT(), ST->getMemOperand());
9956   }
9957
9958   // Only perform this optimization before the types are legal, because we
9959   // don't want to perform this optimization on every DAGCombine invocation.
9960   if (!LegalTypes) {
9961     bool EverChanged = false;
9962
9963     do {
9964       // There can be multiple store sequences on the same chain.
9965       // Keep trying to merge store sequences until we are unable to do so
9966       // or until we merge the last store on the chain.
9967       bool Changed = MergeConsecutiveStores(ST);
9968       EverChanged |= Changed;
9969       if (!Changed) break;
9970     } while (ST->getOpcode() != ISD::DELETED_NODE);
9971
9972     if (EverChanged)
9973       return SDValue(N, 0);
9974   }
9975
9976   return ReduceLoadOpStoreWidth(N);
9977 }
9978
9979 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
9980   SDValue InVec = N->getOperand(0);
9981   SDValue InVal = N->getOperand(1);
9982   SDValue EltNo = N->getOperand(2);
9983   SDLoc dl(N);
9984
9985   // If the inserted element is an UNDEF, just use the input vector.
9986   if (InVal.getOpcode() == ISD::UNDEF)
9987     return InVec;
9988
9989   EVT VT = InVec.getValueType();
9990
9991   // If we can't generate a legal BUILD_VECTOR, exit
9992   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
9993     return SDValue();
9994
9995   // Check that we know which element is being inserted
9996   if (!isa<ConstantSDNode>(EltNo))
9997     return SDValue();
9998   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9999
10000   // Canonicalize insert_vector_elt dag nodes.
10001   // Example:
10002   // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
10003   // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
10004   //
10005   // Do this only if the child insert_vector node has one use; also
10006   // do this only if indices are both constants and Idx1 < Idx0.
10007   if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
10008       && isa<ConstantSDNode>(InVec.getOperand(2))) {
10009     unsigned OtherElt =
10010       cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
10011     if (Elt < OtherElt) {
10012       // Swap nodes.
10013       SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
10014                                   InVec.getOperand(0), InVal, EltNo);
10015       AddToWorklist(NewOp.getNode());
10016       return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
10017                          VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
10018     }
10019   }
10020
10021   // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
10022   // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
10023   // vector elements.
10024   SmallVector<SDValue, 8> Ops;
10025   // Do not combine these two vectors if the output vector will not replace
10026   // the input vector.
10027   if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
10028     Ops.append(InVec.getNode()->op_begin(),
10029                InVec.getNode()->op_end());
10030   } else if (InVec.getOpcode() == ISD::UNDEF) {
10031     unsigned NElts = VT.getVectorNumElements();
10032     Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
10033   } else {
10034     return SDValue();
10035   }
10036
10037   // Insert the element
10038   if (Elt < Ops.size()) {
10039     // All the operands of BUILD_VECTOR must have the same type;
10040     // we enforce that here.
10041     EVT OpVT = Ops[0].getValueType();
10042     if (InVal.getValueType() != OpVT)
10043       InVal = OpVT.bitsGT(InVal.getValueType()) ?
10044                 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
10045                 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
10046     Ops[Elt] = InVal;
10047   }
10048
10049   // Return the new vector
10050   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
10051 }
10052
10053 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
10054     SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
10055   EVT ResultVT = EVE->getValueType(0);
10056   EVT VecEltVT = InVecVT.getVectorElementType();
10057   unsigned Align = OriginalLoad->getAlignment();
10058   unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
10059       VecEltVT.getTypeForEVT(*DAG.getContext()));
10060
10061   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
10062     return SDValue();
10063
10064   Align = NewAlign;
10065
10066   SDValue NewPtr = OriginalLoad->getBasePtr();
10067   SDValue Offset;
10068   EVT PtrType = NewPtr.getValueType();
10069   MachinePointerInfo MPI;
10070   if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
10071     int Elt = ConstEltNo->getZExtValue();
10072     unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
10073     if (TLI.isBigEndian())
10074       PtrOff = InVecVT.getSizeInBits() / 8 - PtrOff;
10075     Offset = DAG.getConstant(PtrOff, PtrType);
10076     MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
10077   } else {
10078     Offset = DAG.getNode(
10079         ISD::MUL, SDLoc(EVE), EltNo.getValueType(), EltNo,
10080         DAG.getConstant(VecEltVT.getStoreSize(), EltNo.getValueType()));
10081     if (TLI.isBigEndian())
10082       Offset = DAG.getNode(
10083           ISD::SUB, SDLoc(EVE), EltNo.getValueType(),
10084           DAG.getConstant(InVecVT.getStoreSize(), EltNo.getValueType()), Offset);
10085     MPI = OriginalLoad->getPointerInfo();
10086   }
10087   NewPtr = DAG.getNode(ISD::ADD, SDLoc(EVE), PtrType, NewPtr, Offset);
10088
10089   // The replacement we need to do here is a little tricky: we need to
10090   // replace an extractelement of a load with a load.
10091   // Use ReplaceAllUsesOfValuesWith to do the replacement.
10092   // Note that this replacement assumes that the extractvalue is the only
10093   // use of the load; that's okay because we don't want to perform this
10094   // transformation in other cases anyway.
10095   SDValue Load;
10096   SDValue Chain;
10097   if (ResultVT.bitsGT(VecEltVT)) {
10098     // If the result type of vextract is wider than the load, then issue an
10099     // extending load instead.
10100     ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, VecEltVT)
10101                                    ? ISD::ZEXTLOAD
10102                                    : ISD::EXTLOAD;
10103     Load = DAG.getExtLoad(
10104         ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI,
10105         VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
10106         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
10107     Chain = Load.getValue(1);
10108   } else {
10109     Load = DAG.getLoad(
10110         VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
10111         OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
10112         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
10113     Chain = Load.getValue(1);
10114     if (ResultVT.bitsLT(VecEltVT))
10115       Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
10116     else
10117       Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
10118   }
10119   WorklistRemover DeadNodes(*this);
10120   SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
10121   SDValue To[] = { Load, Chain };
10122   DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
10123   // Since we're explicitly calling ReplaceAllUses, add the new node to the
10124   // worklist explicitly as well.
10125   AddToWorklist(Load.getNode());
10126   AddUsersToWorklist(Load.getNode()); // Add users too
10127   // Make sure to revisit this node to clean it up; it will usually be dead.
10128   AddToWorklist(EVE);
10129   ++OpsNarrowed;
10130   return SDValue(EVE, 0);
10131 }
10132
10133 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
10134   // (vextract (scalar_to_vector val, 0) -> val
10135   SDValue InVec = N->getOperand(0);
10136   EVT VT = InVec.getValueType();
10137   EVT NVT = N->getValueType(0);
10138
10139   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
10140     // Check if the result type doesn't match the inserted element type. A
10141     // SCALAR_TO_VECTOR may truncate the inserted element and the
10142     // EXTRACT_VECTOR_ELT may widen the extracted vector.
10143     SDValue InOp = InVec.getOperand(0);
10144     if (InOp.getValueType() != NVT) {
10145       assert(InOp.getValueType().isInteger() && NVT.isInteger());
10146       return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
10147     }
10148     return InOp;
10149   }
10150
10151   SDValue EltNo = N->getOperand(1);
10152   bool ConstEltNo = isa<ConstantSDNode>(EltNo);
10153
10154   // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
10155   // We only perform this optimization before the op legalization phase because
10156   // we may introduce new vector instructions which are not backed by TD
10157   // patterns. For example on AVX, extracting elements from a wide vector
10158   // without using extract_subvector. However, if we can find an underlying
10159   // scalar value, then we can always use that.
10160   if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
10161       && ConstEltNo) {
10162     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
10163     int NumElem = VT.getVectorNumElements();
10164     ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
10165     // Find the new index to extract from.
10166     int OrigElt = SVOp->getMaskElt(Elt);
10167
10168     // Extracting an undef index is undef.
10169     if (OrigElt == -1)
10170       return DAG.getUNDEF(NVT);
10171
10172     // Select the right vector half to extract from.
10173     SDValue SVInVec;
10174     if (OrigElt < NumElem) {
10175       SVInVec = InVec->getOperand(0);
10176     } else {
10177       SVInVec = InVec->getOperand(1);
10178       OrigElt -= NumElem;
10179     }
10180
10181     if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
10182       SDValue InOp = SVInVec.getOperand(OrigElt);
10183       if (InOp.getValueType() != NVT) {
10184         assert(InOp.getValueType().isInteger() && NVT.isInteger());
10185         InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
10186       }
10187
10188       return InOp;
10189     }
10190
10191     // FIXME: We should handle recursing on other vector shuffles and
10192     // scalar_to_vector here as well.
10193
10194     if (!LegalOperations) {
10195       EVT IndexTy = TLI.getVectorIdxTy();
10196       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
10197                          SVInVec, DAG.getConstant(OrigElt, IndexTy));
10198     }
10199   }
10200
10201   bool BCNumEltsChanged = false;
10202   EVT ExtVT = VT.getVectorElementType();
10203   EVT LVT = ExtVT;
10204
10205   // If the result of load has to be truncated, then it's not necessarily
10206   // profitable.
10207   if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
10208     return SDValue();
10209
10210   if (InVec.getOpcode() == ISD::BITCAST) {
10211     // Don't duplicate a load with other uses.
10212     if (!InVec.hasOneUse())
10213       return SDValue();
10214
10215     EVT BCVT = InVec.getOperand(0).getValueType();
10216     if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
10217       return SDValue();
10218     if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
10219       BCNumEltsChanged = true;
10220     InVec = InVec.getOperand(0);
10221     ExtVT = BCVT.getVectorElementType();
10222   }
10223
10224   // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
10225   if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
10226       ISD::isNormalLoad(InVec.getNode()) &&
10227       !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
10228     SDValue Index = N->getOperand(1);
10229     if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
10230       return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
10231                                                            OrigLoad);
10232   }
10233
10234   // Perform only after legalization to ensure build_vector / vector_shuffle
10235   // optimizations have already been done.
10236   if (!LegalOperations) return SDValue();
10237
10238   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
10239   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
10240   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
10241
10242   if (ConstEltNo) {
10243     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
10244
10245     LoadSDNode *LN0 = nullptr;
10246     const ShuffleVectorSDNode *SVN = nullptr;
10247     if (ISD::isNormalLoad(InVec.getNode())) {
10248       LN0 = cast<LoadSDNode>(InVec);
10249     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
10250                InVec.getOperand(0).getValueType() == ExtVT &&
10251                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
10252       // Don't duplicate a load with other uses.
10253       if (!InVec.hasOneUse())
10254         return SDValue();
10255
10256       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
10257     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
10258       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
10259       // =>
10260       // (load $addr+1*size)
10261
10262       // Don't duplicate a load with other uses.
10263       if (!InVec.hasOneUse())
10264         return SDValue();
10265
10266       // If the bit convert changed the number of elements, it is unsafe
10267       // to examine the mask.
10268       if (BCNumEltsChanged)
10269         return SDValue();
10270
10271       // Select the input vector, guarding against out of range extract vector.
10272       unsigned NumElems = VT.getVectorNumElements();
10273       int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
10274       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
10275
10276       if (InVec.getOpcode() == ISD::BITCAST) {
10277         // Don't duplicate a load with other uses.
10278         if (!InVec.hasOneUse())
10279           return SDValue();
10280
10281         InVec = InVec.getOperand(0);
10282       }
10283       if (ISD::isNormalLoad(InVec.getNode())) {
10284         LN0 = cast<LoadSDNode>(InVec);
10285         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
10286         EltNo = DAG.getConstant(Elt, EltNo.getValueType());
10287       }
10288     }
10289
10290     // Make sure we found a non-volatile load and the extractelement is
10291     // the only use.
10292     if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
10293       return SDValue();
10294
10295     // If Idx was -1 above, Elt is going to be -1, so just return undef.
10296     if (Elt == -1)
10297       return DAG.getUNDEF(LVT);
10298
10299     return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
10300   }
10301
10302   return SDValue();
10303 }
10304
10305 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
10306 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
10307   // We perform this optimization post type-legalization because
10308   // the type-legalizer often scalarizes integer-promoted vectors.
10309   // Performing this optimization before may create bit-casts which
10310   // will be type-legalized to complex code sequences.
10311   // We perform this optimization only before the operation legalizer because we
10312   // may introduce illegal operations.
10313   if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
10314     return SDValue();
10315
10316   unsigned NumInScalars = N->getNumOperands();
10317   SDLoc dl(N);
10318   EVT VT = N->getValueType(0);
10319
10320   // Check to see if this is a BUILD_VECTOR of a bunch of values
10321   // which come from any_extend or zero_extend nodes. If so, we can create
10322   // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
10323   // optimizations. We do not handle sign-extend because we can't fill the sign
10324   // using shuffles.
10325   EVT SourceType = MVT::Other;
10326   bool AllAnyExt = true;
10327
10328   for (unsigned i = 0; i != NumInScalars; ++i) {
10329     SDValue In = N->getOperand(i);
10330     // Ignore undef inputs.
10331     if (In.getOpcode() == ISD::UNDEF) continue;
10332
10333     bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
10334     bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
10335
10336     // Abort if the element is not an extension.
10337     if (!ZeroExt && !AnyExt) {
10338       SourceType = MVT::Other;
10339       break;
10340     }
10341
10342     // The input is a ZeroExt or AnyExt. Check the original type.
10343     EVT InTy = In.getOperand(0).getValueType();
10344
10345     // Check that all of the widened source types are the same.
10346     if (SourceType == MVT::Other)
10347       // First time.
10348       SourceType = InTy;
10349     else if (InTy != SourceType) {
10350       // Multiple income types. Abort.
10351       SourceType = MVT::Other;
10352       break;
10353     }
10354
10355     // Check if all of the extends are ANY_EXTENDs.
10356     AllAnyExt &= AnyExt;
10357   }
10358
10359   // In order to have valid types, all of the inputs must be extended from the
10360   // same source type and all of the inputs must be any or zero extend.
10361   // Scalar sizes must be a power of two.
10362   EVT OutScalarTy = VT.getScalarType();
10363   bool ValidTypes = SourceType != MVT::Other &&
10364                  isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
10365                  isPowerOf2_32(SourceType.getSizeInBits());
10366
10367   // Create a new simpler BUILD_VECTOR sequence which other optimizations can
10368   // turn into a single shuffle instruction.
10369   if (!ValidTypes)
10370     return SDValue();
10371
10372   bool isLE = TLI.isLittleEndian();
10373   unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
10374   assert(ElemRatio > 1 && "Invalid element size ratio");
10375   SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
10376                                DAG.getConstant(0, SourceType);
10377
10378   unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
10379   SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
10380
10381   // Populate the new build_vector
10382   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10383     SDValue Cast = N->getOperand(i);
10384     assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
10385             Cast.getOpcode() == ISD::ZERO_EXTEND ||
10386             Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
10387     SDValue In;
10388     if (Cast.getOpcode() == ISD::UNDEF)
10389       In = DAG.getUNDEF(SourceType);
10390     else
10391       In = Cast->getOperand(0);
10392     unsigned Index = isLE ? (i * ElemRatio) :
10393                             (i * ElemRatio + (ElemRatio - 1));
10394
10395     assert(Index < Ops.size() && "Invalid index");
10396     Ops[Index] = In;
10397   }
10398
10399   // The type of the new BUILD_VECTOR node.
10400   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
10401   assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
10402          "Invalid vector size");
10403   // Check if the new vector type is legal.
10404   if (!isTypeLegal(VecVT)) return SDValue();
10405
10406   // Make the new BUILD_VECTOR.
10407   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
10408
10409   // The new BUILD_VECTOR node has the potential to be further optimized.
10410   AddToWorklist(BV.getNode());
10411   // Bitcast to the desired type.
10412   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
10413 }
10414
10415 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
10416   EVT VT = N->getValueType(0);
10417
10418   unsigned NumInScalars = N->getNumOperands();
10419   SDLoc dl(N);
10420
10421   EVT SrcVT = MVT::Other;
10422   unsigned Opcode = ISD::DELETED_NODE;
10423   unsigned NumDefs = 0;
10424
10425   for (unsigned i = 0; i != NumInScalars; ++i) {
10426     SDValue In = N->getOperand(i);
10427     unsigned Opc = In.getOpcode();
10428
10429     if (Opc == ISD::UNDEF)
10430       continue;
10431
10432     // If all scalar values are floats and converted from integers.
10433     if (Opcode == ISD::DELETED_NODE &&
10434         (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
10435       Opcode = Opc;
10436     }
10437
10438     if (Opc != Opcode)
10439       return SDValue();
10440
10441     EVT InVT = In.getOperand(0).getValueType();
10442
10443     // If all scalar values are typed differently, bail out. It's chosen to
10444     // simplify BUILD_VECTOR of integer types.
10445     if (SrcVT == MVT::Other)
10446       SrcVT = InVT;
10447     if (SrcVT != InVT)
10448       return SDValue();
10449     NumDefs++;
10450   }
10451
10452   // If the vector has just one element defined, it's not worth to fold it into
10453   // a vectorized one.
10454   if (NumDefs < 2)
10455     return SDValue();
10456
10457   assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
10458          && "Should only handle conversion from integer to float.");
10459   assert(SrcVT != MVT::Other && "Cannot determine source type!");
10460
10461   EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
10462
10463   if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
10464     return SDValue();
10465
10466   SmallVector<SDValue, 8> Opnds;
10467   for (unsigned i = 0; i != NumInScalars; ++i) {
10468     SDValue In = N->getOperand(i);
10469
10470     if (In.getOpcode() == ISD::UNDEF)
10471       Opnds.push_back(DAG.getUNDEF(SrcVT));
10472     else
10473       Opnds.push_back(In.getOperand(0));
10474   }
10475   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
10476   AddToWorklist(BV.getNode());
10477
10478   return DAG.getNode(Opcode, dl, VT, BV);
10479 }
10480
10481 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
10482   unsigned NumInScalars = N->getNumOperands();
10483   SDLoc dl(N);
10484   EVT VT = N->getValueType(0);
10485
10486   // A vector built entirely of undefs is undef.
10487   if (ISD::allOperandsUndef(N))
10488     return DAG.getUNDEF(VT);
10489
10490   SDValue V = reduceBuildVecExtToExtBuildVec(N);
10491   if (V.getNode())
10492     return V;
10493
10494   V = reduceBuildVecConvertToConvertBuildVec(N);
10495   if (V.getNode())
10496     return V;
10497
10498   // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
10499   // operations.  If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
10500   // at most two distinct vectors, turn this into a shuffle node.
10501
10502   // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
10503   if (!isTypeLegal(VT))
10504     return SDValue();
10505
10506   // May only combine to shuffle after legalize if shuffle is legal.
10507   if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
10508     return SDValue();
10509
10510   SDValue VecIn1, VecIn2;
10511   for (unsigned i = 0; i != NumInScalars; ++i) {
10512     // Ignore undef inputs.
10513     if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
10514
10515     // If this input is something other than a EXTRACT_VECTOR_ELT with a
10516     // constant index, bail out.
10517     if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10518         !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
10519       VecIn1 = VecIn2 = SDValue(nullptr, 0);
10520       break;
10521     }
10522
10523     // We allow up to two distinct input vectors.
10524     SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
10525     if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
10526       continue;
10527
10528     if (!VecIn1.getNode()) {
10529       VecIn1 = ExtractedFromVec;
10530     } else if (!VecIn2.getNode()) {
10531       VecIn2 = ExtractedFromVec;
10532     } else {
10533       // Too many inputs.
10534       VecIn1 = VecIn2 = SDValue(nullptr, 0);
10535       break;
10536     }
10537   }
10538
10539   // If everything is good, we can make a shuffle operation.
10540   if (VecIn1.getNode()) {
10541     SmallVector<int, 8> Mask;
10542     for (unsigned i = 0; i != NumInScalars; ++i) {
10543       if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
10544         Mask.push_back(-1);
10545         continue;
10546       }
10547
10548       // If extracting from the first vector, just use the index directly.
10549       SDValue Extract = N->getOperand(i);
10550       SDValue ExtVal = Extract.getOperand(1);
10551       if (Extract.getOperand(0) == VecIn1) {
10552         unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10553         if (ExtIndex > VT.getVectorNumElements())
10554           return SDValue();
10555
10556         Mask.push_back(ExtIndex);
10557         continue;
10558       }
10559
10560       // Otherwise, use InIdx + VecSize
10561       unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10562       Mask.push_back(Idx+NumInScalars);
10563     }
10564
10565     // We can't generate a shuffle node with mismatched input and output types.
10566     // Attempt to transform a single input vector to the correct type.
10567     if ((VT != VecIn1.getValueType())) {
10568       // We don't support shuffeling between TWO values of different types.
10569       if (VecIn2.getNode())
10570         return SDValue();
10571
10572       // We only support widening of vectors which are half the size of the
10573       // output registers. For example XMM->YMM widening on X86 with AVX.
10574       if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits())
10575         return SDValue();
10576
10577       // If the input vector type has a different base type to the output
10578       // vector type, bail out.
10579       if (VecIn1.getValueType().getVectorElementType() !=
10580           VT.getVectorElementType())
10581         return SDValue();
10582
10583       // Widen the input vector by adding undef values.
10584       VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10585                            VecIn1, DAG.getUNDEF(VecIn1.getValueType()));
10586     }
10587
10588     // If VecIn2 is unused then change it to undef.
10589     VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
10590
10591     // Check that we were able to transform all incoming values to the same
10592     // type.
10593     if (VecIn2.getValueType() != VecIn1.getValueType() ||
10594         VecIn1.getValueType() != VT)
10595           return SDValue();
10596
10597     // Return the new VECTOR_SHUFFLE node.
10598     SDValue Ops[2];
10599     Ops[0] = VecIn1;
10600     Ops[1] = VecIn2;
10601     return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
10602   }
10603
10604   return SDValue();
10605 }
10606
10607 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
10608   // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
10609   // EXTRACT_SUBVECTOR operations.  If so, and if the EXTRACT_SUBVECTOR vector
10610   // inputs come from at most two distinct vectors, turn this into a shuffle
10611   // node.
10612
10613   // If we only have one input vector, we don't need to do any concatenation.
10614   if (N->getNumOperands() == 1)
10615     return N->getOperand(0);
10616
10617   // Check if all of the operands are undefs.
10618   EVT VT = N->getValueType(0);
10619   if (ISD::allOperandsUndef(N))
10620     return DAG.getUNDEF(VT);
10621
10622   // Optimize concat_vectors where one of the vectors is undef.
10623   if (N->getNumOperands() == 2 &&
10624       N->getOperand(1)->getOpcode() == ISD::UNDEF) {
10625     SDValue In = N->getOperand(0);
10626     assert(In.getValueType().isVector() && "Must concat vectors");
10627
10628     // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
10629     if (In->getOpcode() == ISD::BITCAST &&
10630         !In->getOperand(0)->getValueType(0).isVector()) {
10631       SDValue Scalar = In->getOperand(0);
10632       EVT SclTy = Scalar->getValueType(0);
10633
10634       if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
10635         return SDValue();
10636
10637       EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
10638                                  VT.getSizeInBits() / SclTy.getSizeInBits());
10639       if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
10640         return SDValue();
10641
10642       SDLoc dl = SDLoc(N);
10643       SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
10644       return DAG.getNode(ISD::BITCAST, dl, VT, Res);
10645     }
10646   }
10647
10648   // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
10649   // -> (BUILD_VECTOR A, B, ..., C, D, ...)
10650   if (N->getNumOperands() == 2 &&
10651       N->getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
10652       N->getOperand(1).getOpcode() == ISD::BUILD_VECTOR) {
10653     EVT VT = N->getValueType(0);
10654     SDValue N0 = N->getOperand(0);
10655     SDValue N1 = N->getOperand(1);
10656     SmallVector<SDValue, 8> Opnds;
10657     unsigned BuildVecNumElts =  N0.getNumOperands();
10658
10659     EVT SclTy0 = N0.getOperand(0)->getValueType(0);
10660     EVT SclTy1 = N1.getOperand(0)->getValueType(0);
10661     if (SclTy0.isFloatingPoint()) {
10662       for (unsigned i = 0; i != BuildVecNumElts; ++i)
10663         Opnds.push_back(N0.getOperand(i));
10664       for (unsigned i = 0; i != BuildVecNumElts; ++i)
10665         Opnds.push_back(N1.getOperand(i));
10666     } else {
10667       // If BUILD_VECTOR are from built from integer, they may have different
10668       // operand types. Get the smaller type and truncate all operands to it.
10669       EVT MinTy = SclTy0.bitsLE(SclTy1) ? SclTy0 : SclTy1;
10670       for (unsigned i = 0; i != BuildVecNumElts; ++i)
10671         Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy,
10672                         N0.getOperand(i)));
10673       for (unsigned i = 0; i != BuildVecNumElts; ++i)
10674         Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy,
10675                         N1.getOperand(i)));
10676     }
10677
10678     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
10679   }
10680
10681   // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
10682   // nodes often generate nop CONCAT_VECTOR nodes.
10683   // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
10684   // place the incoming vectors at the exact same location.
10685   SDValue SingleSource = SDValue();
10686   unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
10687
10688   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10689     SDValue Op = N->getOperand(i);
10690
10691     if (Op.getOpcode() == ISD::UNDEF)
10692       continue;
10693
10694     // Check if this is the identity extract:
10695     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
10696       return SDValue();
10697
10698     // Find the single incoming vector for the extract_subvector.
10699     if (SingleSource.getNode()) {
10700       if (Op.getOperand(0) != SingleSource)
10701         return SDValue();
10702     } else {
10703       SingleSource = Op.getOperand(0);
10704
10705       // Check the source type is the same as the type of the result.
10706       // If not, this concat may extend the vector, so we can not
10707       // optimize it away.
10708       if (SingleSource.getValueType() != N->getValueType(0))
10709         return SDValue();
10710     }
10711
10712     unsigned IdentityIndex = i * PartNumElem;
10713     ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10714     // The extract index must be constant.
10715     if (!CS)
10716       return SDValue();
10717
10718     // Check that we are reading from the identity index.
10719     if (CS->getZExtValue() != IdentityIndex)
10720       return SDValue();
10721   }
10722
10723   if (SingleSource.getNode())
10724     return SingleSource;
10725
10726   return SDValue();
10727 }
10728
10729 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
10730   EVT NVT = N->getValueType(0);
10731   SDValue V = N->getOperand(0);
10732
10733   if (V->getOpcode() == ISD::CONCAT_VECTORS) {
10734     // Combine:
10735     //    (extract_subvec (concat V1, V2, ...), i)
10736     // Into:
10737     //    Vi if possible
10738     // Only operand 0 is checked as 'concat' assumes all inputs of the same
10739     // type.
10740     if (V->getOperand(0).getValueType() != NVT)
10741       return SDValue();
10742     unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10743     unsigned NumElems = NVT.getVectorNumElements();
10744     assert((Idx % NumElems) == 0 &&
10745            "IDX in concat is not a multiple of the result vector length.");
10746     return V->getOperand(Idx / NumElems);
10747   }
10748
10749   // Skip bitcasting
10750   if (V->getOpcode() == ISD::BITCAST)
10751     V = V.getOperand(0);
10752
10753   if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
10754     SDLoc dl(N);
10755     // Handle only simple case where vector being inserted and vector
10756     // being extracted are of same type, and are half size of larger vectors.
10757     EVT BigVT = V->getOperand(0).getValueType();
10758     EVT SmallVT = V->getOperand(1).getValueType();
10759     if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
10760       return SDValue();
10761
10762     // Only handle cases where both indexes are constants with the same type.
10763     ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10764     ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
10765
10766     if (InsIdx && ExtIdx &&
10767         InsIdx->getValueType(0).getSizeInBits() <= 64 &&
10768         ExtIdx->getValueType(0).getSizeInBits() <= 64) {
10769       // Combine:
10770       //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
10771       // Into:
10772       //    indices are equal or bit offsets are equal => V1
10773       //    otherwise => (extract_subvec V1, ExtIdx)
10774       if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
10775           ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
10776         return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
10777       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
10778                          DAG.getNode(ISD::BITCAST, dl,
10779                                      N->getOperand(0).getValueType(),
10780                                      V->getOperand(0)), N->getOperand(1));
10781     }
10782   }
10783
10784   return SDValue();
10785 }
10786
10787 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
10788                                                  SDValue V, SelectionDAG &DAG) {
10789   SDLoc DL(V);
10790   EVT VT = V.getValueType();
10791
10792   switch (V.getOpcode()) {
10793   default:
10794     return V;
10795
10796   case ISD::CONCAT_VECTORS: {
10797     EVT OpVT = V->getOperand(0).getValueType();
10798     int OpSize = OpVT.getVectorNumElements();
10799     SmallBitVector OpUsedElements(OpSize, false);
10800     bool FoundSimplification = false;
10801     SmallVector<SDValue, 4> NewOps;
10802     NewOps.reserve(V->getNumOperands());
10803     for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
10804       SDValue Op = V->getOperand(i);
10805       bool OpUsed = false;
10806       for (int j = 0; j < OpSize; ++j)
10807         if (UsedElements[i * OpSize + j]) {
10808           OpUsedElements[j] = true;
10809           OpUsed = true;
10810         }
10811       NewOps.push_back(
10812           OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
10813                  : DAG.getUNDEF(OpVT));
10814       FoundSimplification |= Op == NewOps.back();
10815       OpUsedElements.reset();
10816     }
10817     if (FoundSimplification)
10818       V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
10819     return V;
10820   }
10821
10822   case ISD::INSERT_SUBVECTOR: {
10823     SDValue BaseV = V->getOperand(0);
10824     SDValue SubV = V->getOperand(1);
10825     auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
10826     if (!IdxN)
10827       return V;
10828
10829     int SubSize = SubV.getValueType().getVectorNumElements();
10830     int Idx = IdxN->getZExtValue();
10831     bool SubVectorUsed = false;
10832     SmallBitVector SubUsedElements(SubSize, false);
10833     for (int i = 0; i < SubSize; ++i)
10834       if (UsedElements[i + Idx]) {
10835         SubVectorUsed = true;
10836         SubUsedElements[i] = true;
10837         UsedElements[i + Idx] = false;
10838       }
10839
10840     // Now recurse on both the base and sub vectors.
10841     SDValue SimplifiedSubV =
10842         SubVectorUsed
10843             ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
10844             : DAG.getUNDEF(SubV.getValueType());
10845     SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
10846     if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
10847       V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
10848                       SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
10849     return V;
10850   }
10851   }
10852 }
10853
10854 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
10855                                        SDValue N1, SelectionDAG &DAG) {
10856   EVT VT = SVN->getValueType(0);
10857   int NumElts = VT.getVectorNumElements();
10858   SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
10859   for (int M : SVN->getMask())
10860     if (M >= 0 && M < NumElts)
10861       N0UsedElements[M] = true;
10862     else if (M >= NumElts)
10863       N1UsedElements[M - NumElts] = true;
10864
10865   SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
10866   SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
10867   if (S0 == N0 && S1 == N1)
10868     return SDValue();
10869
10870   return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
10871 }
10872
10873 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat.
10874 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
10875   EVT VT = N->getValueType(0);
10876   unsigned NumElts = VT.getVectorNumElements();
10877
10878   SDValue N0 = N->getOperand(0);
10879   SDValue N1 = N->getOperand(1);
10880   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10881
10882   SmallVector<SDValue, 4> Ops;
10883   EVT ConcatVT = N0.getOperand(0).getValueType();
10884   unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
10885   unsigned NumConcats = NumElts / NumElemsPerConcat;
10886
10887   // Look at every vector that's inserted. We're looking for exact
10888   // subvector-sized copies from a concatenated vector
10889   for (unsigned I = 0; I != NumConcats; ++I) {
10890     // Make sure we're dealing with a copy.
10891     unsigned Begin = I * NumElemsPerConcat;
10892     bool AllUndef = true, NoUndef = true;
10893     for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
10894       if (SVN->getMaskElt(J) >= 0)
10895         AllUndef = false;
10896       else
10897         NoUndef = false;
10898     }
10899
10900     if (NoUndef) {
10901       if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
10902         return SDValue();
10903
10904       for (unsigned J = 1; J != NumElemsPerConcat; ++J)
10905         if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
10906           return SDValue();
10907
10908       unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
10909       if (FirstElt < N0.getNumOperands())
10910         Ops.push_back(N0.getOperand(FirstElt));
10911       else
10912         Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
10913
10914     } else if (AllUndef) {
10915       Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
10916     } else { // Mixed with general masks and undefs, can't do optimization.
10917       return SDValue();
10918     }
10919   }
10920
10921   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
10922 }
10923
10924 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
10925   EVT VT = N->getValueType(0);
10926   unsigned NumElts = VT.getVectorNumElements();
10927
10928   SDValue N0 = N->getOperand(0);
10929   SDValue N1 = N->getOperand(1);
10930
10931   assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
10932
10933   // Canonicalize shuffle undef, undef -> undef
10934   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
10935     return DAG.getUNDEF(VT);
10936
10937   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10938
10939   // Canonicalize shuffle v, v -> v, undef
10940   if (N0 == N1) {
10941     SmallVector<int, 8> NewMask;
10942     for (unsigned i = 0; i != NumElts; ++i) {
10943       int Idx = SVN->getMaskElt(i);
10944       if (Idx >= (int)NumElts) Idx -= NumElts;
10945       NewMask.push_back(Idx);
10946     }
10947     return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
10948                                 &NewMask[0]);
10949   }
10950
10951   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
10952   if (N0.getOpcode() == ISD::UNDEF) {
10953     SmallVector<int, 8> NewMask;
10954     for (unsigned i = 0; i != NumElts; ++i) {
10955       int Idx = SVN->getMaskElt(i);
10956       if (Idx >= 0) {
10957         if (Idx >= (int)NumElts)
10958           Idx -= NumElts;
10959         else
10960           Idx = -1; // remove reference to lhs
10961       }
10962       NewMask.push_back(Idx);
10963     }
10964     return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
10965                                 &NewMask[0]);
10966   }
10967
10968   // Remove references to rhs if it is undef
10969   if (N1.getOpcode() == ISD::UNDEF) {
10970     bool Changed = false;
10971     SmallVector<int, 8> NewMask;
10972     for (unsigned i = 0; i != NumElts; ++i) {
10973       int Idx = SVN->getMaskElt(i);
10974       if (Idx >= (int)NumElts) {
10975         Idx = -1;
10976         Changed = true;
10977       }
10978       NewMask.push_back(Idx);
10979     }
10980     if (Changed)
10981       return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
10982   }
10983
10984   // If it is a splat, check if the argument vector is another splat or a
10985   // build_vector with all scalar elements the same.
10986   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
10987     SDNode *V = N0.getNode();
10988
10989     // If this is a bit convert that changes the element type of the vector but
10990     // not the number of vector elements, look through it.  Be careful not to
10991     // look though conversions that change things like v4f32 to v2f64.
10992     if (V->getOpcode() == ISD::BITCAST) {
10993       SDValue ConvInput = V->getOperand(0);
10994       if (ConvInput.getValueType().isVector() &&
10995           ConvInput.getValueType().getVectorNumElements() == NumElts)
10996         V = ConvInput.getNode();
10997     }
10998
10999     if (V->getOpcode() == ISD::BUILD_VECTOR) {
11000       assert(V->getNumOperands() == NumElts &&
11001              "BUILD_VECTOR has wrong number of operands");
11002       SDValue Base;
11003       bool AllSame = true;
11004       for (unsigned i = 0; i != NumElts; ++i) {
11005         if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
11006           Base = V->getOperand(i);
11007           break;
11008         }
11009       }
11010       // Splat of <u, u, u, u>, return <u, u, u, u>
11011       if (!Base.getNode())
11012         return N0;
11013       for (unsigned i = 0; i != NumElts; ++i) {
11014         if (V->getOperand(i) != Base) {
11015           AllSame = false;
11016           break;
11017         }
11018       }
11019       // Splat of <x, x, x, x>, return <x, x, x, x>
11020       if (AllSame)
11021         return N0;
11022     }
11023   }
11024
11025   // There are various patterns used to build up a vector from smaller vectors,
11026   // subvectors, or elements. Scan chains of these and replace unused insertions
11027   // or components with undef.
11028   if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
11029     return S;
11030
11031   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
11032       Level < AfterLegalizeVectorOps &&
11033       (N1.getOpcode() == ISD::UNDEF ||
11034       (N1.getOpcode() == ISD::CONCAT_VECTORS &&
11035        N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
11036     SDValue V = partitionShuffleOfConcats(N, DAG);
11037
11038     if (V.getNode())
11039       return V;
11040   }
11041
11042   // If this shuffle node is simply a swizzle of another shuffle node,
11043   // then try to simplify it.
11044   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
11045       N1.getOpcode() == ISD::UNDEF) {
11046
11047     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
11048
11049     // The incoming shuffle must be of the same type as the result of the
11050     // current shuffle.
11051     assert(OtherSV->getOperand(0).getValueType() == VT &&
11052            "Shuffle types don't match");
11053
11054     SmallVector<int, 4> Mask;
11055     // Compute the combined shuffle mask.
11056     for (unsigned i = 0; i != NumElts; ++i) {
11057       int Idx = SVN->getMaskElt(i);
11058       assert(Idx < (int)NumElts && "Index references undef operand");
11059       // Next, this index comes from the first value, which is the incoming
11060       // shuffle. Adopt the incoming index.
11061       if (Idx >= 0)
11062         Idx = OtherSV->getMaskElt(Idx);
11063       Mask.push_back(Idx);
11064     }
11065
11066     // Check if all indices in Mask are Undef. In case, propagate Undef.
11067     bool isUndefMask = true;
11068     for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
11069       isUndefMask &= Mask[i] < 0;
11070
11071     if (isUndefMask)
11072       return DAG.getUNDEF(VT);
11073
11074     bool CommuteOperands = false;
11075     if (N0.getOperand(1).getOpcode() != ISD::UNDEF) {
11076       // To be valid, the combine shuffle mask should only reference elements
11077       // from one of the two vectors in input to the inner shufflevector.
11078       bool IsValidMask = true;
11079       for (unsigned i = 0; i != NumElts && IsValidMask; ++i)
11080         // See if the combined mask only reference undefs or elements coming
11081         // from the first shufflevector operand.
11082         IsValidMask = Mask[i] < 0 || (unsigned)Mask[i] < NumElts;
11083
11084       if (!IsValidMask) {
11085         IsValidMask = true;
11086         for (unsigned i = 0; i != NumElts && IsValidMask; ++i)
11087           // Check that all the elements come from the second shuffle operand.
11088           IsValidMask = Mask[i] < 0 || (unsigned)Mask[i] >= NumElts;
11089         CommuteOperands = IsValidMask;
11090       }
11091
11092       // Early exit if the combined shuffle mask is not valid.
11093       if (!IsValidMask)
11094         return SDValue();
11095     }
11096
11097     // See if this pair of shuffles can be safely folded according to either
11098     // of the following rules:
11099     //   shuffle(shuffle(x, y), undef) -> x
11100     //   shuffle(shuffle(x, undef), undef) -> x
11101     //   shuffle(shuffle(x, y), undef) -> y
11102     bool IsIdentityMask = true;
11103     unsigned BaseMaskIndex = CommuteOperands ? NumElts : 0;
11104     for (unsigned i = 0; i != NumElts && IsIdentityMask; ++i) {
11105       // Skip Undefs.
11106       if (Mask[i] < 0)
11107         continue;
11108
11109       // The combined shuffle must map each index to itself.
11110       IsIdentityMask = (unsigned)Mask[i] == i + BaseMaskIndex;
11111     }
11112
11113     if (IsIdentityMask) {
11114       if (CommuteOperands)
11115         // optimize shuffle(shuffle(x, y), undef) -> y.
11116         return OtherSV->getOperand(1);
11117
11118       // optimize shuffle(shuffle(x, undef), undef) -> x
11119       // optimize shuffle(shuffle(x, y), undef) -> x
11120       return OtherSV->getOperand(0);
11121     }
11122
11123     // It may still be beneficial to combine the two shuffles if the
11124     // resulting shuffle is legal.
11125     if (TLI.isTypeLegal(VT)) {
11126       if (!CommuteOperands) {
11127         if (TLI.isShuffleMaskLegal(Mask, VT))
11128           // shuffle(shuffle(x, undef, M1), undef, M2) -> shuffle(x, undef, M3).
11129           // shuffle(shuffle(x, y, M1), undef, M2) -> shuffle(x, undef, M3)
11130           return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0), N1,
11131                                       &Mask[0]);
11132       } else {
11133         // Compute the commuted shuffle mask.
11134         for (unsigned i = 0; i != NumElts; ++i) {
11135           int idx = Mask[i];
11136           if (idx < 0)
11137             continue;
11138           else if (idx < (int)NumElts)
11139             Mask[i] = idx + NumElts;
11140           else
11141             Mask[i] = idx - NumElts;
11142         }
11143
11144         if (TLI.isShuffleMaskLegal(Mask, VT))
11145           //   shuffle(shuffle(x, y, M1), undef, M2) -> shuffle(y, undef, M3)
11146           return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(1), N1,
11147                                       &Mask[0]);
11148       }
11149     }
11150   }
11151
11152   // Canonicalize shuffles according to rules:
11153   //  shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
11154   //  shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
11155   //  shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
11156   if (N1.getOpcode() == ISD::VECTOR_SHUFFLE && N0.getOpcode() != ISD::UNDEF &&
11157       N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
11158       TLI.isTypeLegal(VT)) {
11159     // The incoming shuffle must be of the same type as the result of the
11160     // current shuffle.
11161     assert(N1->getOperand(0).getValueType() == VT &&
11162            "Shuffle types don't match");
11163
11164     SDValue SV0 = N1->getOperand(0);
11165     SDValue SV1 = N1->getOperand(1);
11166     bool HasSameOp0 = N0 == SV0;
11167     bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
11168     if (HasSameOp0 || IsSV1Undef || N0 == SV1)
11169       // Commute the operands of this shuffle so that next rule
11170       // will trigger.
11171       return DAG.getCommutedVectorShuffle(*SVN);
11172   }
11173
11174   // Try to fold according to rules:
11175   //   shuffle(shuffle(A, B, M0), B, M1) -> shuffle(A, B, M2)
11176   //   shuffle(shuffle(A, B, M0), A, M1) -> shuffle(A, B, M2)
11177   //   shuffle(shuffle(A, Undef, M0), B, M1) -> shuffle(A, B, M2)
11178   //   shuffle(shuffle(A, Undef, M0), A, M1) -> shuffle(A, Undef, M2)
11179   // Don't try to fold shuffles with illegal type.
11180   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
11181       N1.getOpcode() != ISD::UNDEF && TLI.isTypeLegal(VT)) {
11182     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
11183
11184     // The incoming shuffle must be of the same type as the result of the
11185     // current shuffle.
11186     assert(OtherSV->getOperand(0).getValueType() == VT &&
11187            "Shuffle types don't match");
11188
11189     SDValue SV0 = OtherSV->getOperand(0);
11190     SDValue SV1 = OtherSV->getOperand(1);
11191     bool HasSameOp0 = N1 == SV0;
11192     bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
11193     if (!HasSameOp0 && !IsSV1Undef && N1 != SV1)
11194       // Early exit.
11195       return SDValue();
11196
11197     SmallVector<int, 4> Mask;
11198     // Compute the combined shuffle mask for a shuffle with SV0 as the first
11199     // operand, and SV1 as the second operand.
11200     for (unsigned i = 0; i != NumElts; ++i) {
11201       int Idx = SVN->getMaskElt(i);
11202       if (Idx < 0) {
11203         // Propagate Undef.
11204         Mask.push_back(Idx);
11205         continue;
11206       }
11207
11208       if (Idx < (int)NumElts) {
11209         Idx = OtherSV->getMaskElt(Idx);
11210         if (IsSV1Undef && Idx >= (int) NumElts)
11211           Idx = -1;  // Propagate Undef.
11212       } else
11213         Idx = HasSameOp0 ? Idx - NumElts : Idx;
11214
11215       Mask.push_back(Idx);
11216     }
11217
11218     // Check if all indices in Mask are Undef. In case, propagate Undef.
11219     bool isUndefMask = true;
11220     for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
11221       isUndefMask &= Mask[i] < 0;
11222
11223     if (isUndefMask)
11224       return DAG.getUNDEF(VT);
11225
11226     // Avoid introducing shuffles with illegal mask.
11227     if (TLI.isShuffleMaskLegal(Mask, VT)) {
11228       if (IsSV1Undef)
11229         //   shuffle(shuffle(A, Undef, M0), B, M1) -> shuffle(A, B, M2)
11230         //   shuffle(shuffle(A, Undef, M0), A, M1) -> shuffle(A, Undef, M2)
11231         return DAG.getVectorShuffle(VT, SDLoc(N), SV0, N1, &Mask[0]);
11232       return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
11233     }
11234   }
11235
11236   return SDValue();
11237 }
11238
11239 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
11240   SDValue N0 = N->getOperand(0);
11241   SDValue N2 = N->getOperand(2);
11242
11243   // If the input vector is a concatenation, and the insert replaces
11244   // one of the halves, we can optimize into a single concat_vectors.
11245   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
11246       N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
11247     APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
11248     EVT VT = N->getValueType(0);
11249
11250     // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
11251     // (concat_vectors Z, Y)
11252     if (InsIdx == 0)
11253       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
11254                          N->getOperand(1), N0.getOperand(1));
11255
11256     // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
11257     // (concat_vectors X, Z)
11258     if (InsIdx == VT.getVectorNumElements()/2)
11259       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
11260                          N0.getOperand(0), N->getOperand(1));
11261   }
11262
11263   return SDValue();
11264 }
11265
11266 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
11267 /// with the destination vector and a zero vector.
11268 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
11269 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
11270 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
11271   EVT VT = N->getValueType(0);
11272   SDLoc dl(N);
11273   SDValue LHS = N->getOperand(0);
11274   SDValue RHS = N->getOperand(1);
11275   if (N->getOpcode() == ISD::AND) {
11276     if (RHS.getOpcode() == ISD::BITCAST)
11277       RHS = RHS.getOperand(0);
11278     if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
11279       SmallVector<int, 8> Indices;
11280       unsigned NumElts = RHS.getNumOperands();
11281       for (unsigned i = 0; i != NumElts; ++i) {
11282         SDValue Elt = RHS.getOperand(i);
11283         if (!isa<ConstantSDNode>(Elt))
11284           return SDValue();
11285
11286         if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
11287           Indices.push_back(i);
11288         else if (cast<ConstantSDNode>(Elt)->isNullValue())
11289           Indices.push_back(NumElts);
11290         else
11291           return SDValue();
11292       }
11293
11294       // Let's see if the target supports this vector_shuffle.
11295       EVT RVT = RHS.getValueType();
11296       if (!TLI.isVectorClearMaskLegal(Indices, RVT))
11297         return SDValue();
11298
11299       // Return the new VECTOR_SHUFFLE node.
11300       EVT EltVT = RVT.getVectorElementType();
11301       SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
11302                                      DAG.getConstant(0, EltVT));
11303       SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), RVT, ZeroOps);
11304       LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
11305       SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
11306       return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
11307     }
11308   }
11309
11310   return SDValue();
11311 }
11312
11313 /// Visit a binary vector operation, like ADD.
11314 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
11315   assert(N->getValueType(0).isVector() &&
11316          "SimplifyVBinOp only works on vectors!");
11317
11318   SDValue LHS = N->getOperand(0);
11319   SDValue RHS = N->getOperand(1);
11320   SDValue Shuffle = XformToShuffleWithZero(N);
11321   if (Shuffle.getNode()) return Shuffle;
11322
11323   // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
11324   // this operation.
11325   if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
11326       RHS.getOpcode() == ISD::BUILD_VECTOR) {
11327     // Check if both vectors are constants. If not bail out.
11328     if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
11329           cast<BuildVectorSDNode>(RHS)->isConstant()))
11330       return SDValue();
11331
11332     SmallVector<SDValue, 8> Ops;
11333     for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
11334       SDValue LHSOp = LHS.getOperand(i);
11335       SDValue RHSOp = RHS.getOperand(i);
11336
11337       // Can't fold divide by zero.
11338       if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
11339           N->getOpcode() == ISD::FDIV) {
11340         if ((RHSOp.getOpcode() == ISD::Constant &&
11341              cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
11342             (RHSOp.getOpcode() == ISD::ConstantFP &&
11343              cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
11344           break;
11345       }
11346
11347       EVT VT = LHSOp.getValueType();
11348       EVT RVT = RHSOp.getValueType();
11349       if (RVT != VT) {
11350         // Integer BUILD_VECTOR operands may have types larger than the element
11351         // size (e.g., when the element type is not legal).  Prior to type
11352         // legalization, the types may not match between the two BUILD_VECTORS.
11353         // Truncate one of the operands to make them match.
11354         if (RVT.getSizeInBits() > VT.getSizeInBits()) {
11355           RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
11356         } else {
11357           LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
11358           VT = RVT;
11359         }
11360       }
11361       SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
11362                                    LHSOp, RHSOp);
11363       if (FoldOp.getOpcode() != ISD::UNDEF &&
11364           FoldOp.getOpcode() != ISD::Constant &&
11365           FoldOp.getOpcode() != ISD::ConstantFP)
11366         break;
11367       Ops.push_back(FoldOp);
11368       AddToWorklist(FoldOp.getNode());
11369     }
11370
11371     if (Ops.size() == LHS.getNumOperands())
11372       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
11373   }
11374
11375   // Type legalization might introduce new shuffles in the DAG.
11376   // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
11377   //   -> (shuffle (VBinOp (A, B)), Undef, Mask).
11378   if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
11379       isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
11380       LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
11381       RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
11382     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
11383     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
11384
11385     if (SVN0->getMask().equals(SVN1->getMask())) {
11386       EVT VT = N->getValueType(0);
11387       SDValue UndefVector = LHS.getOperand(1);
11388       SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
11389                                      LHS.getOperand(0), RHS.getOperand(0));
11390       AddUsersToWorklist(N);
11391       return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
11392                                   &SVN0->getMask()[0]);
11393     }
11394   }
11395
11396   return SDValue();
11397 }
11398
11399 /// Visit a binary vector operation, like FABS/FNEG.
11400 SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
11401   assert(N->getValueType(0).isVector() &&
11402          "SimplifyVUnaryOp only works on vectors!");
11403
11404   SDValue N0 = N->getOperand(0);
11405
11406   if (N0.getOpcode() != ISD::BUILD_VECTOR)
11407     return SDValue();
11408
11409   // Operand is a BUILD_VECTOR node, see if we can constant fold it.
11410   SmallVector<SDValue, 8> Ops;
11411   for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
11412     SDValue Op = N0.getOperand(i);
11413     if (Op.getOpcode() != ISD::UNDEF &&
11414         Op.getOpcode() != ISD::ConstantFP)
11415       break;
11416     EVT EltVT = Op.getValueType();
11417     SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op);
11418     if (FoldOp.getOpcode() != ISD::UNDEF &&
11419         FoldOp.getOpcode() != ISD::ConstantFP)
11420       break;
11421     Ops.push_back(FoldOp);
11422     AddToWorklist(FoldOp.getNode());
11423   }
11424
11425   if (Ops.size() != N0.getNumOperands())
11426     return SDValue();
11427
11428   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), N0.getValueType(), Ops);
11429 }
11430
11431 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
11432                                     SDValue N1, SDValue N2){
11433   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
11434
11435   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
11436                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
11437
11438   // If we got a simplified select_cc node back from SimplifySelectCC, then
11439   // break it down into a new SETCC node, and a new SELECT node, and then return
11440   // the SELECT node, since we were called with a SELECT node.
11441   if (SCC.getNode()) {
11442     // Check to see if we got a select_cc back (to turn into setcc/select).
11443     // Otherwise, just return whatever node we got back, like fabs.
11444     if (SCC.getOpcode() == ISD::SELECT_CC) {
11445       SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
11446                                   N0.getValueType(),
11447                                   SCC.getOperand(0), SCC.getOperand(1),
11448                                   SCC.getOperand(4));
11449       AddToWorklist(SETCC.getNode());
11450       return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
11451                            SCC.getOperand(2), SCC.getOperand(3));
11452     }
11453
11454     return SCC;
11455   }
11456   return SDValue();
11457 }
11458
11459 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
11460 /// being selected between, see if we can simplify the select.  Callers of this
11461 /// should assume that TheSelect is deleted if this returns true.  As such, they
11462 /// should return the appropriate thing (e.g. the node) back to the top-level of
11463 /// the DAG combiner loop to avoid it being looked at.
11464 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
11465                                     SDValue RHS) {
11466
11467   // Cannot simplify select with vector condition
11468   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
11469
11470   // If this is a select from two identical things, try to pull the operation
11471   // through the select.
11472   if (LHS.getOpcode() != RHS.getOpcode() ||
11473       !LHS.hasOneUse() || !RHS.hasOneUse())
11474     return false;
11475
11476   // If this is a load and the token chain is identical, replace the select
11477   // of two loads with a load through a select of the address to load from.
11478   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
11479   // constants have been dropped into the constant pool.
11480   if (LHS.getOpcode() == ISD::LOAD) {
11481     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
11482     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
11483
11484     // Token chains must be identical.
11485     if (LHS.getOperand(0) != RHS.getOperand(0) ||
11486         // Do not let this transformation reduce the number of volatile loads.
11487         LLD->isVolatile() || RLD->isVolatile() ||
11488         // If this is an EXTLOAD, the VT's must match.
11489         LLD->getMemoryVT() != RLD->getMemoryVT() ||
11490         // If this is an EXTLOAD, the kind of extension must match.
11491         (LLD->getExtensionType() != RLD->getExtensionType() &&
11492          // The only exception is if one of the extensions is anyext.
11493          LLD->getExtensionType() != ISD::EXTLOAD &&
11494          RLD->getExtensionType() != ISD::EXTLOAD) ||
11495         // FIXME: this discards src value information.  This is
11496         // over-conservative. It would be beneficial to be able to remember
11497         // both potential memory locations.  Since we are discarding
11498         // src value info, don't do the transformation if the memory
11499         // locations are not in the default address space.
11500         LLD->getPointerInfo().getAddrSpace() != 0 ||
11501         RLD->getPointerInfo().getAddrSpace() != 0 ||
11502         !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
11503                                       LLD->getBasePtr().getValueType()))
11504       return false;
11505
11506     // Check that the select condition doesn't reach either load.  If so,
11507     // folding this will induce a cycle into the DAG.  If not, this is safe to
11508     // xform, so create a select of the addresses.
11509     SDValue Addr;
11510     if (TheSelect->getOpcode() == ISD::SELECT) {
11511       SDNode *CondNode = TheSelect->getOperand(0).getNode();
11512       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
11513           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
11514         return false;
11515       // The loads must not depend on one another.
11516       if (LLD->isPredecessorOf(RLD) ||
11517           RLD->isPredecessorOf(LLD))
11518         return false;
11519       Addr = DAG.getSelect(SDLoc(TheSelect),
11520                            LLD->getBasePtr().getValueType(),
11521                            TheSelect->getOperand(0), LLD->getBasePtr(),
11522                            RLD->getBasePtr());
11523     } else {  // Otherwise SELECT_CC
11524       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
11525       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
11526
11527       if ((LLD->hasAnyUseOfValue(1) &&
11528            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
11529           (RLD->hasAnyUseOfValue(1) &&
11530            (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
11531         return false;
11532
11533       Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
11534                          LLD->getBasePtr().getValueType(),
11535                          TheSelect->getOperand(0),
11536                          TheSelect->getOperand(1),
11537                          LLD->getBasePtr(), RLD->getBasePtr(),
11538                          TheSelect->getOperand(4));
11539     }
11540
11541     SDValue Load;
11542     // It is safe to replace the two loads if they have different alignments,
11543     // but the new load must be the minimum (most restrictive) alignment of the
11544     // inputs.
11545     bool isInvariant = LLD->isInvariant() & RLD->isInvariant();
11546     unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
11547     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
11548       Load = DAG.getLoad(TheSelect->getValueType(0),
11549                          SDLoc(TheSelect),
11550                          // FIXME: Discards pointer and AA info.
11551                          LLD->getChain(), Addr, MachinePointerInfo(),
11552                          LLD->isVolatile(), LLD->isNonTemporal(),
11553                          isInvariant, Alignment);
11554     } else {
11555       Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
11556                             RLD->getExtensionType() : LLD->getExtensionType(),
11557                             SDLoc(TheSelect),
11558                             TheSelect->getValueType(0),
11559                             // FIXME: Discards pointer and AA info.
11560                             LLD->getChain(), Addr, MachinePointerInfo(),
11561                             LLD->getMemoryVT(), LLD->isVolatile(),
11562                             LLD->isNonTemporal(), isInvariant, Alignment);
11563     }
11564
11565     // Users of the select now use the result of the load.
11566     CombineTo(TheSelect, Load);
11567
11568     // Users of the old loads now use the new load's chain.  We know the
11569     // old-load value is dead now.
11570     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
11571     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
11572     return true;
11573   }
11574
11575   return false;
11576 }
11577
11578 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
11579 /// where 'cond' is the comparison specified by CC.
11580 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
11581                                       SDValue N2, SDValue N3,
11582                                       ISD::CondCode CC, bool NotExtCompare) {
11583   // (x ? y : y) -> y.
11584   if (N2 == N3) return N2;
11585
11586   EVT VT = N2.getValueType();
11587   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
11588   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
11589   ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
11590
11591   // Determine if the condition we're dealing with is constant
11592   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
11593                               N0, N1, CC, DL, false);
11594   if (SCC.getNode()) AddToWorklist(SCC.getNode());
11595   ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
11596
11597   // fold select_cc true, x, y -> x
11598   if (SCCC && !SCCC->isNullValue())
11599     return N2;
11600   // fold select_cc false, x, y -> y
11601   if (SCCC && SCCC->isNullValue())
11602     return N3;
11603
11604   // Check to see if we can simplify the select into an fabs node
11605   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
11606     // Allow either -0.0 or 0.0
11607     if (CFP->getValueAPF().isZero()) {
11608       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
11609       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
11610           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
11611           N2 == N3.getOperand(0))
11612         return DAG.getNode(ISD::FABS, DL, VT, N0);
11613
11614       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
11615       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
11616           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
11617           N2.getOperand(0) == N3)
11618         return DAG.getNode(ISD::FABS, DL, VT, N3);
11619     }
11620   }
11621
11622   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
11623   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
11624   // in it.  This is a win when the constant is not otherwise available because
11625   // it replaces two constant pool loads with one.  We only do this if the FP
11626   // type is known to be legal, because if it isn't, then we are before legalize
11627   // types an we want the other legalization to happen first (e.g. to avoid
11628   // messing with soft float) and if the ConstantFP is not legal, because if
11629   // it is legal, we may not need to store the FP constant in a constant pool.
11630   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
11631     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
11632       if (TLI.isTypeLegal(N2.getValueType()) &&
11633           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
11634                TargetLowering::Legal &&
11635            !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
11636            !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
11637           // If both constants have multiple uses, then we won't need to do an
11638           // extra load, they are likely around in registers for other users.
11639           (TV->hasOneUse() || FV->hasOneUse())) {
11640         Constant *Elts[] = {
11641           const_cast<ConstantFP*>(FV->getConstantFPValue()),
11642           const_cast<ConstantFP*>(TV->getConstantFPValue())
11643         };
11644         Type *FPTy = Elts[0]->getType();
11645         const DataLayout &TD = *TLI.getDataLayout();
11646
11647         // Create a ConstantArray of the two constants.
11648         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
11649         SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
11650                                             TD.getPrefTypeAlignment(FPTy));
11651         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
11652
11653         // Get the offsets to the 0 and 1 element of the array so that we can
11654         // select between them.
11655         SDValue Zero = DAG.getIntPtrConstant(0);
11656         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
11657         SDValue One = DAG.getIntPtrConstant(EltSize);
11658
11659         SDValue Cond = DAG.getSetCC(DL,
11660                                     getSetCCResultType(N0.getValueType()),
11661                                     N0, N1, CC);
11662         AddToWorklist(Cond.getNode());
11663         SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
11664                                           Cond, One, Zero);
11665         AddToWorklist(CstOffset.getNode());
11666         CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
11667                             CstOffset);
11668         AddToWorklist(CPIdx.getNode());
11669         return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
11670                            MachinePointerInfo::getConstantPool(), false,
11671                            false, false, Alignment);
11672
11673       }
11674     }
11675
11676   // Check to see if we can perform the "gzip trick", transforming
11677   // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
11678   if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
11679       (N1C->isNullValue() ||                         // (a < 0) ? b : 0
11680        (N1C->getAPIntValue() == 1 && N0 == N2))) {   // (a < 1) ? a : 0
11681     EVT XType = N0.getValueType();
11682     EVT AType = N2.getValueType();
11683     if (XType.bitsGE(AType)) {
11684       // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
11685       // single-bit constant.
11686       if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
11687         unsigned ShCtV = N2C->getAPIntValue().logBase2();
11688         ShCtV = XType.getSizeInBits()-ShCtV-1;
11689         SDValue ShCt = DAG.getConstant(ShCtV,
11690                                        getShiftAmountTy(N0.getValueType()));
11691         SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
11692                                     XType, N0, ShCt);
11693         AddToWorklist(Shift.getNode());
11694
11695         if (XType.bitsGT(AType)) {
11696           Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11697           AddToWorklist(Shift.getNode());
11698         }
11699
11700         return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11701       }
11702
11703       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
11704                                   XType, N0,
11705                                   DAG.getConstant(XType.getSizeInBits()-1,
11706                                          getShiftAmountTy(N0.getValueType())));
11707       AddToWorklist(Shift.getNode());
11708
11709       if (XType.bitsGT(AType)) {
11710         Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11711         AddToWorklist(Shift.getNode());
11712       }
11713
11714       return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11715     }
11716   }
11717
11718   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
11719   // where y is has a single bit set.
11720   // A plaintext description would be, we can turn the SELECT_CC into an AND
11721   // when the condition can be materialized as an all-ones register.  Any
11722   // single bit-test can be materialized as an all-ones register with
11723   // shift-left and shift-right-arith.
11724   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
11725       N0->getValueType(0) == VT &&
11726       N1C && N1C->isNullValue() &&
11727       N2C && N2C->isNullValue()) {
11728     SDValue AndLHS = N0->getOperand(0);
11729     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
11730     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
11731       // Shift the tested bit over the sign bit.
11732       APInt AndMask = ConstAndRHS->getAPIntValue();
11733       SDValue ShlAmt =
11734         DAG.getConstant(AndMask.countLeadingZeros(),
11735                         getShiftAmountTy(AndLHS.getValueType()));
11736       SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
11737
11738       // Now arithmetic right shift it all the way over, so the result is either
11739       // all-ones, or zero.
11740       SDValue ShrAmt =
11741         DAG.getConstant(AndMask.getBitWidth()-1,
11742                         getShiftAmountTy(Shl.getValueType()));
11743       SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
11744
11745       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
11746     }
11747   }
11748
11749   // fold select C, 16, 0 -> shl C, 4
11750   if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
11751       TLI.getBooleanContents(N0.getValueType()) ==
11752           TargetLowering::ZeroOrOneBooleanContent) {
11753
11754     // If the caller doesn't want us to simplify this into a zext of a compare,
11755     // don't do it.
11756     if (NotExtCompare && N2C->getAPIntValue() == 1)
11757       return SDValue();
11758
11759     // Get a SetCC of the condition
11760     // NOTE: Don't create a SETCC if it's not legal on this target.
11761     if (!LegalOperations ||
11762         TLI.isOperationLegal(ISD::SETCC,
11763           LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
11764       SDValue Temp, SCC;
11765       // cast from setcc result type to select result type
11766       if (LegalTypes) {
11767         SCC  = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
11768                             N0, N1, CC);
11769         if (N2.getValueType().bitsLT(SCC.getValueType()))
11770           Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
11771                                         N2.getValueType());
11772         else
11773           Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11774                              N2.getValueType(), SCC);
11775       } else {
11776         SCC  = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
11777         Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11778                            N2.getValueType(), SCC);
11779       }
11780
11781       AddToWorklist(SCC.getNode());
11782       AddToWorklist(Temp.getNode());
11783
11784       if (N2C->getAPIntValue() == 1)
11785         return Temp;
11786
11787       // shl setcc result by log2 n2c
11788       return DAG.getNode(
11789           ISD::SHL, DL, N2.getValueType(), Temp,
11790           DAG.getConstant(N2C->getAPIntValue().logBase2(),
11791                           getShiftAmountTy(Temp.getValueType())));
11792     }
11793   }
11794
11795   // Check to see if this is the equivalent of setcc
11796   // FIXME: Turn all of these into setcc if setcc if setcc is legal
11797   // otherwise, go ahead with the folds.
11798   if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
11799     EVT XType = N0.getValueType();
11800     if (!LegalOperations ||
11801         TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
11802       SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
11803       if (Res.getValueType() != VT)
11804         Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
11805       return Res;
11806     }
11807
11808     // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
11809     if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
11810         (!LegalOperations ||
11811          TLI.isOperationLegal(ISD::CTLZ, XType))) {
11812       SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
11813       return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
11814                          DAG.getConstant(Log2_32(XType.getSizeInBits()),
11815                                        getShiftAmountTy(Ctlz.getValueType())));
11816     }
11817     // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
11818     if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
11819       SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
11820                                   XType, DAG.getConstant(0, XType), N0);
11821       SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
11822       return DAG.getNode(ISD::SRL, DL, XType,
11823                          DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
11824                          DAG.getConstant(XType.getSizeInBits()-1,
11825                                          getShiftAmountTy(XType)));
11826     }
11827     // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
11828     if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
11829       SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
11830                                  DAG.getConstant(XType.getSizeInBits()-1,
11831                                          getShiftAmountTy(N0.getValueType())));
11832       return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
11833     }
11834   }
11835
11836   // Check to see if this is an integer abs.
11837   // select_cc setg[te] X,  0,  X, -X ->
11838   // select_cc setgt    X, -1,  X, -X ->
11839   // select_cc setl[te] X,  0, -X,  X ->
11840   // select_cc setlt    X,  1, -X,  X ->
11841   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
11842   if (N1C) {
11843     ConstantSDNode *SubC = nullptr;
11844     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
11845          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
11846         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
11847       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
11848     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
11849               (N1C->isOne() && CC == ISD::SETLT)) &&
11850              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
11851       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
11852
11853     EVT XType = N0.getValueType();
11854     if (SubC && SubC->isNullValue() && XType.isInteger()) {
11855       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
11856                                   N0,
11857                                   DAG.getConstant(XType.getSizeInBits()-1,
11858                                          getShiftAmountTy(N0.getValueType())));
11859       SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
11860                                 XType, N0, Shift);
11861       AddToWorklist(Shift.getNode());
11862       AddToWorklist(Add.getNode());
11863       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
11864     }
11865   }
11866
11867   return SDValue();
11868 }
11869
11870 /// This is a stub for TargetLowering::SimplifySetCC.
11871 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
11872                                    SDValue N1, ISD::CondCode Cond,
11873                                    SDLoc DL, bool foldBooleans) {
11874   TargetLowering::DAGCombinerInfo
11875     DagCombineInfo(DAG, Level, false, this);
11876   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
11877 }
11878
11879 /// Given an ISD::SDIV node expressing a divide by constant, return
11880 /// a DAG expression to select that will generate the same value by multiplying
11881 /// by a magic number.
11882 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
11883 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
11884   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11885   if (!C)
11886     return SDValue();
11887
11888   // Avoid division by zero.
11889   if (!C->getAPIntValue())
11890     return SDValue();
11891
11892   std::vector<SDNode*> Built;
11893   SDValue S =
11894       TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
11895
11896   for (SDNode *N : Built)
11897     AddToWorklist(N);
11898   return S;
11899 }
11900
11901 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
11902 /// DAG expression that will generate the same value by right shifting.
11903 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
11904   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11905   if (!C)
11906     return SDValue();
11907
11908   // Avoid division by zero.
11909   if (!C->getAPIntValue())
11910     return SDValue();
11911
11912   std::vector<SDNode *> Built;
11913   SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
11914
11915   for (SDNode *N : Built)
11916     AddToWorklist(N);
11917   return S;
11918 }
11919
11920 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
11921 /// expression that will generate the same value by multiplying by a magic
11922 /// number.
11923 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
11924 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
11925   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11926   if (!C)
11927     return SDValue();
11928
11929   // Avoid division by zero.
11930   if (!C->getAPIntValue())
11931     return SDValue();
11932
11933   std::vector<SDNode*> Built;
11934   SDValue S =
11935       TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
11936
11937   for (SDNode *N : Built)
11938     AddToWorklist(N);
11939   return S;
11940 }
11941
11942 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op) {
11943   if (Level >= AfterLegalizeDAG)
11944     return SDValue();
11945
11946   // Expose the DAG combiner to the target combiner implementations.
11947   TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
11948
11949   unsigned Iterations = 0;
11950   if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) {
11951     if (Iterations) {
11952       // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
11953       // For the reciprocal, we need to find the zero of the function:
11954       //   F(X) = A X - 1 [which has a zero at X = 1/A]
11955       //     =>
11956       //   X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
11957       //     does not require additional intermediate precision]
11958       EVT VT = Op.getValueType();
11959       SDLoc DL(Op);
11960       SDValue FPOne = DAG.getConstantFP(1.0, VT);
11961
11962       AddToWorklist(Est.getNode());
11963
11964       // Newton iterations: Est = Est + Est (1 - Arg * Est)
11965       for (unsigned i = 0; i < Iterations; ++i) {
11966         SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est);
11967         AddToWorklist(NewEst.getNode());
11968
11969         NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst);
11970         AddToWorklist(NewEst.getNode());
11971
11972         NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
11973         AddToWorklist(NewEst.getNode());
11974
11975         Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst);
11976         AddToWorklist(Est.getNode());
11977       }
11978     }
11979     return Est;
11980   }
11981
11982   return SDValue();
11983 }
11984
11985 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
11986 /// For the reciprocal sqrt, we need to find the zero of the function:
11987 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
11988 ///     =>
11989 ///   X_{i+1} = X_i (1.5 - A X_i^2 / 2)
11990 /// As a result, we precompute A/2 prior to the iteration loop.
11991 SDValue DAGCombiner::BuildRsqrtNROneConst(SDValue Arg, SDValue Est,
11992                                           unsigned Iterations) {
11993   EVT VT = Arg.getValueType();
11994   SDLoc DL(Arg);
11995   SDValue ThreeHalves = DAG.getConstantFP(1.5, VT);
11996
11997   // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
11998   // this entire sequence requires only one FP constant.
11999   SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg);
12000   AddToWorklist(HalfArg.getNode());
12001
12002   HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg);
12003   AddToWorklist(HalfArg.getNode());
12004
12005   // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
12006   for (unsigned i = 0; i < Iterations; ++i) {
12007     SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
12008     AddToWorklist(NewEst.getNode());
12009
12010     NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst);
12011     AddToWorklist(NewEst.getNode());
12012
12013     NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst);
12014     AddToWorklist(NewEst.getNode());
12015
12016     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
12017     AddToWorklist(Est.getNode());
12018   }
12019   return Est;
12020 }
12021
12022 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
12023 /// For the reciprocal sqrt, we need to find the zero of the function:
12024 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
12025 ///     =>
12026 ///   X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
12027 SDValue DAGCombiner::BuildRsqrtNRTwoConst(SDValue Arg, SDValue Est,
12028                                           unsigned Iterations) {
12029   EVT VT = Arg.getValueType();
12030   SDLoc DL(Arg);
12031   SDValue MinusThree = DAG.getConstantFP(-3.0, VT);
12032   SDValue MinusHalf = DAG.getConstantFP(-0.5, VT);
12033
12034   // Newton iterations: Est = -0.5 * Est * (-3.0 + Arg * Est * Est)
12035   for (unsigned i = 0; i < Iterations; ++i) {
12036     SDValue HalfEst = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf);
12037     AddToWorklist(HalfEst.getNode());
12038
12039     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
12040     AddToWorklist(Est.getNode());
12041
12042     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg);
12043     AddToWorklist(Est.getNode());
12044
12045     Est = DAG.getNode(ISD::FADD, DL, VT, Est, MinusThree);
12046     AddToWorklist(Est.getNode());
12047
12048     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, HalfEst);
12049     AddToWorklist(Est.getNode());
12050   }
12051   return Est;
12052 }
12053
12054 SDValue DAGCombiner::BuildRsqrtEstimate(SDValue Op) {
12055   if (Level >= AfterLegalizeDAG)
12056     return SDValue();
12057
12058   // Expose the DAG combiner to the target combiner implementations.
12059   TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
12060   unsigned Iterations = 0;
12061   bool UseOneConstNR = false;
12062   if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations, UseOneConstNR)) {
12063     AddToWorklist(Est.getNode());
12064     if (Iterations) {
12065       Est = UseOneConstNR ?
12066         BuildRsqrtNROneConst(Op, Est, Iterations) :
12067         BuildRsqrtNRTwoConst(Op, Est, Iterations);
12068     }
12069     return Est;
12070   }
12071
12072   return SDValue();
12073 }
12074
12075 /// Return true if base is a frame index, which is known not to alias with
12076 /// anything but itself.  Provides base object and offset as results.
12077 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
12078                            const GlobalValue *&GV, const void *&CV) {
12079   // Assume it is a primitive operation.
12080   Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
12081
12082   // If it's an adding a simple constant then integrate the offset.
12083   if (Base.getOpcode() == ISD::ADD) {
12084     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
12085       Base = Base.getOperand(0);
12086       Offset += C->getZExtValue();
12087     }
12088   }
12089
12090   // Return the underlying GlobalValue, and update the Offset.  Return false
12091   // for GlobalAddressSDNode since the same GlobalAddress may be represented
12092   // by multiple nodes with different offsets.
12093   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
12094     GV = G->getGlobal();
12095     Offset += G->getOffset();
12096     return false;
12097   }
12098
12099   // Return the underlying Constant value, and update the Offset.  Return false
12100   // for ConstantSDNodes since the same constant pool entry may be represented
12101   // by multiple nodes with different offsets.
12102   if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
12103     CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
12104                                          : (const void *)C->getConstVal();
12105     Offset += C->getOffset();
12106     return false;
12107   }
12108   // If it's any of the following then it can't alias with anything but itself.
12109   return isa<FrameIndexSDNode>(Base);
12110 }
12111
12112 /// Return true if there is any possibility that the two addresses overlap.
12113 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
12114   // If they are the same then they must be aliases.
12115   if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
12116
12117   // If they are both volatile then they cannot be reordered.
12118   if (Op0->isVolatile() && Op1->isVolatile()) return true;
12119
12120   // Gather base node and offset information.
12121   SDValue Base1, Base2;
12122   int64_t Offset1, Offset2;
12123   const GlobalValue *GV1, *GV2;
12124   const void *CV1, *CV2;
12125   bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
12126                                       Base1, Offset1, GV1, CV1);
12127   bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
12128                                       Base2, Offset2, GV2, CV2);
12129
12130   // If they have a same base address then check to see if they overlap.
12131   if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
12132     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
12133              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
12134
12135   // It is possible for different frame indices to alias each other, mostly
12136   // when tail call optimization reuses return address slots for arguments.
12137   // To catch this case, look up the actual index of frame indices to compute
12138   // the real alias relationship.
12139   if (isFrameIndex1 && isFrameIndex2) {
12140     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12141     Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
12142     Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
12143     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
12144              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
12145   }
12146
12147   // Otherwise, if we know what the bases are, and they aren't identical, then
12148   // we know they cannot alias.
12149   if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
12150     return false;
12151
12152   // If we know required SrcValue1 and SrcValue2 have relatively large alignment
12153   // compared to the size and offset of the access, we may be able to prove they
12154   // do not alias.  This check is conservative for now to catch cases created by
12155   // splitting vector types.
12156   if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
12157       (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
12158       (Op0->getMemoryVT().getSizeInBits() >> 3 ==
12159        Op1->getMemoryVT().getSizeInBits() >> 3) &&
12160       (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
12161     int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
12162     int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
12163
12164     // There is no overlap between these relatively aligned accesses of similar
12165     // size, return no alias.
12166     if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
12167         (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
12168       return false;
12169   }
12170
12171   bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
12172                    ? CombinerGlobalAA
12173                    : DAG.getSubtarget().useAA();
12174 #ifndef NDEBUG
12175   if (CombinerAAOnlyFunc.getNumOccurrences() &&
12176       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
12177     UseAA = false;
12178 #endif
12179   if (UseAA &&
12180       Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
12181     // Use alias analysis information.
12182     int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
12183                                  Op1->getSrcValueOffset());
12184     int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
12185         Op0->getSrcValueOffset() - MinOffset;
12186     int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
12187         Op1->getSrcValueOffset() - MinOffset;
12188     AliasAnalysis::AliasResult AAResult =
12189         AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(),
12190                                          Overlap1,
12191                                          UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
12192                  AliasAnalysis::Location(Op1->getMemOperand()->getValue(),
12193                                          Overlap2,
12194                                          UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
12195     if (AAResult == AliasAnalysis::NoAlias)
12196       return false;
12197   }
12198
12199   // Otherwise we have to assume they alias.
12200   return true;
12201 }
12202
12203 /// Walk up chain skipping non-aliasing memory nodes,
12204 /// looking for aliasing nodes and adding them to the Aliases vector.
12205 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
12206                                    SmallVectorImpl<SDValue> &Aliases) {
12207   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
12208   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
12209
12210   // Get alias information for node.
12211   bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
12212
12213   // Starting off.
12214   Chains.push_back(OriginalChain);
12215   unsigned Depth = 0;
12216
12217   // Look at each chain and determine if it is an alias.  If so, add it to the
12218   // aliases list.  If not, then continue up the chain looking for the next
12219   // candidate.
12220   while (!Chains.empty()) {
12221     SDValue Chain = Chains.back();
12222     Chains.pop_back();
12223
12224     // For TokenFactor nodes, look at each operand and only continue up the
12225     // chain until we find two aliases.  If we've seen two aliases, assume we'll
12226     // find more and revert to original chain since the xform is unlikely to be
12227     // profitable.
12228     //
12229     // FIXME: The depth check could be made to return the last non-aliasing
12230     // chain we found before we hit a tokenfactor rather than the original
12231     // chain.
12232     if (Depth > 6 || Aliases.size() == 2) {
12233       Aliases.clear();
12234       Aliases.push_back(OriginalChain);
12235       return;
12236     }
12237
12238     // Don't bother if we've been before.
12239     if (!Visited.insert(Chain.getNode()))
12240       continue;
12241
12242     switch (Chain.getOpcode()) {
12243     case ISD::EntryToken:
12244       // Entry token is ideal chain operand, but handled in FindBetterChain.
12245       break;
12246
12247     case ISD::LOAD:
12248     case ISD::STORE: {
12249       // Get alias information for Chain.
12250       bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
12251           !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
12252
12253       // If chain is alias then stop here.
12254       if (!(IsLoad && IsOpLoad) &&
12255           isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
12256         Aliases.push_back(Chain);
12257       } else {
12258         // Look further up the chain.
12259         Chains.push_back(Chain.getOperand(0));
12260         ++Depth;
12261       }
12262       break;
12263     }
12264
12265     case ISD::TokenFactor:
12266       // We have to check each of the operands of the token factor for "small"
12267       // token factors, so we queue them up.  Adding the operands to the queue
12268       // (stack) in reverse order maintains the original order and increases the
12269       // likelihood that getNode will find a matching token factor (CSE.)
12270       if (Chain.getNumOperands() > 16) {
12271         Aliases.push_back(Chain);
12272         break;
12273       }
12274       for (unsigned n = Chain.getNumOperands(); n;)
12275         Chains.push_back(Chain.getOperand(--n));
12276       ++Depth;
12277       break;
12278
12279     default:
12280       // For all other instructions we will just have to take what we can get.
12281       Aliases.push_back(Chain);
12282       break;
12283     }
12284   }
12285
12286   // We need to be careful here to also search for aliases through the
12287   // value operand of a store, etc. Consider the following situation:
12288   //   Token1 = ...
12289   //   L1 = load Token1, %52
12290   //   S1 = store Token1, L1, %51
12291   //   L2 = load Token1, %52+8
12292   //   S2 = store Token1, L2, %51+8
12293   //   Token2 = Token(S1, S2)
12294   //   L3 = load Token2, %53
12295   //   S3 = store Token2, L3, %52
12296   //   L4 = load Token2, %53+8
12297   //   S4 = store Token2, L4, %52+8
12298   // If we search for aliases of S3 (which loads address %52), and we look
12299   // only through the chain, then we'll miss the trivial dependence on L1
12300   // (which also loads from %52). We then might change all loads and
12301   // stores to use Token1 as their chain operand, which could result in
12302   // copying %53 into %52 before copying %52 into %51 (which should
12303   // happen first).
12304   //
12305   // The problem is, however, that searching for such data dependencies
12306   // can become expensive, and the cost is not directly related to the
12307   // chain depth. Instead, we'll rule out such configurations here by
12308   // insisting that we've visited all chain users (except for users
12309   // of the original chain, which is not necessary). When doing this,
12310   // we need to look through nodes we don't care about (otherwise, things
12311   // like register copies will interfere with trivial cases).
12312
12313   SmallVector<const SDNode *, 16> Worklist;
12314   for (const SDNode *N : Visited)
12315     if (N != OriginalChain.getNode())
12316       Worklist.push_back(N);
12317
12318   while (!Worklist.empty()) {
12319     const SDNode *M = Worklist.pop_back_val();
12320
12321     // We have already visited M, and want to make sure we've visited any uses
12322     // of M that we care about. For uses that we've not visisted, and don't
12323     // care about, queue them to the worklist.
12324
12325     for (SDNode::use_iterator UI = M->use_begin(),
12326          UIE = M->use_end(); UI != UIE; ++UI)
12327       if (UI.getUse().getValueType() == MVT::Other && Visited.insert(*UI)) {
12328         if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
12329           // We've not visited this use, and we care about it (it could have an
12330           // ordering dependency with the original node).
12331           Aliases.clear();
12332           Aliases.push_back(OriginalChain);
12333           return;
12334         }
12335
12336         // We've not visited this use, but we don't care about it. Mark it as
12337         // visited and enqueue it to the worklist.
12338         Worklist.push_back(*UI);
12339       }
12340   }
12341 }
12342
12343 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
12344 /// (aliasing node.)
12345 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
12346   SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
12347
12348   // Accumulate all the aliases to this node.
12349   GatherAllAliases(N, OldChain, Aliases);
12350
12351   // If no operands then chain to entry token.
12352   if (Aliases.size() == 0)
12353     return DAG.getEntryNode();
12354
12355   // If a single operand then chain to it.  We don't need to revisit it.
12356   if (Aliases.size() == 1)
12357     return Aliases[0];
12358
12359   // Construct a custom tailored token factor.
12360   return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
12361 }
12362
12363 /// This is the entry point for the file.
12364 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
12365                            CodeGenOpt::Level OptLevel) {
12366   /// This is the main entry point to this class.
12367   DAGCombiner(*this, AA, OptLevel).Run(Level);
12368 }