Normally an 'optnone' function goes through fast-isel, which does not
[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   // Early exit if this basic block is in an optnone function.
1159   AttributeSet FnAttrs =
1160     DAG.getMachineFunction().getFunction()->getAttributes();
1161   if (FnAttrs.hasAttribute(AttributeSet::FunctionIndex,
1162                            Attribute::OptimizeNone))
1163     return;
1164
1165   // Add all the dag nodes to the worklist.
1166   for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1167        E = DAG.allnodes_end(); I != E; ++I)
1168     AddToWorklist(I);
1169
1170   // Create a dummy node (which is not added to allnodes), that adds a reference
1171   // to the root node, preventing it from being deleted, and tracking any
1172   // changes of the root.
1173   HandleSDNode Dummy(DAG.getRoot());
1174
1175   // while the worklist isn't empty, find a node and
1176   // try and combine it.
1177   while (!WorklistMap.empty()) {
1178     SDNode *N;
1179     // The Worklist holds the SDNodes in order, but it may contain null entries.
1180     do {
1181       N = Worklist.pop_back_val();
1182     } while (!N);
1183
1184     bool GoodWorklistEntry = WorklistMap.erase(N);
1185     (void)GoodWorklistEntry;
1186     assert(GoodWorklistEntry &&
1187            "Found a worklist entry without a corresponding map entry!");
1188
1189     // If N has no uses, it is dead.  Make sure to revisit all N's operands once
1190     // N is deleted from the DAG, since they too may now be dead or may have a
1191     // reduced number of uses, allowing other xforms.
1192     if (recursivelyDeleteUnusedNodes(N))
1193       continue;
1194
1195     WorklistRemover DeadNodes(*this);
1196
1197     // If this combine is running after legalizing the DAG, re-legalize any
1198     // nodes pulled off the worklist.
1199     if (Level == AfterLegalizeDAG) {
1200       SmallSetVector<SDNode *, 16> UpdatedNodes;
1201       bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1202
1203       for (SDNode *LN : UpdatedNodes) {
1204         AddToWorklist(LN);
1205         AddUsersToWorklist(LN);
1206       }
1207       if (!NIsValid)
1208         continue;
1209     }
1210
1211     DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1212
1213     // Add any operands of the new node which have not yet been combined to the
1214     // worklist as well. Because the worklist uniques things already, this
1215     // won't repeatedly process the same operand.
1216     CombinedNodes.insert(N);
1217     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1218       if (!CombinedNodes.count(N->getOperand(i).getNode()))
1219         AddToWorklist(N->getOperand(i).getNode());
1220
1221     SDValue RV = combine(N);
1222
1223     if (!RV.getNode())
1224       continue;
1225
1226     ++NodesCombined;
1227
1228     // If we get back the same node we passed in, rather than a new node or
1229     // zero, we know that the node must have defined multiple values and
1230     // CombineTo was used.  Since CombineTo takes care of the worklist
1231     // mechanics for us, we have no work to do in this case.
1232     if (RV.getNode() == N)
1233       continue;
1234
1235     assert(N->getOpcode() != ISD::DELETED_NODE &&
1236            RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1237            "Node was deleted but visit returned new node!");
1238
1239     DEBUG(dbgs() << " ... into: ";
1240           RV.getNode()->dump(&DAG));
1241
1242     // Transfer debug value.
1243     DAG.TransferDbgValues(SDValue(N, 0), RV);
1244     if (N->getNumValues() == RV.getNode()->getNumValues())
1245       DAG.ReplaceAllUsesWith(N, RV.getNode());
1246     else {
1247       assert(N->getValueType(0) == RV.getValueType() &&
1248              N->getNumValues() == 1 && "Type mismatch");
1249       SDValue OpV = RV;
1250       DAG.ReplaceAllUsesWith(N, &OpV);
1251     }
1252
1253     // Push the new node and any users onto the worklist
1254     AddToWorklist(RV.getNode());
1255     AddUsersToWorklist(RV.getNode());
1256
1257     // Finally, if the node is now dead, remove it from the graph.  The node
1258     // may not be dead if the replacement process recursively simplified to
1259     // something else needing this node. This will also take care of adding any
1260     // operands which have lost a user to the worklist.
1261     recursivelyDeleteUnusedNodes(N);
1262   }
1263
1264   // If the root changed (e.g. it was a dead load, update the root).
1265   DAG.setRoot(Dummy.getValue());
1266   DAG.RemoveDeadNodes();
1267 }
1268
1269 SDValue DAGCombiner::visit(SDNode *N) {
1270   switch (N->getOpcode()) {
1271   default: break;
1272   case ISD::TokenFactor:        return visitTokenFactor(N);
1273   case ISD::MERGE_VALUES:       return visitMERGE_VALUES(N);
1274   case ISD::ADD:                return visitADD(N);
1275   case ISD::SUB:                return visitSUB(N);
1276   case ISD::ADDC:               return visitADDC(N);
1277   case ISD::SUBC:               return visitSUBC(N);
1278   case ISD::ADDE:               return visitADDE(N);
1279   case ISD::SUBE:               return visitSUBE(N);
1280   case ISD::MUL:                return visitMUL(N);
1281   case ISD::SDIV:               return visitSDIV(N);
1282   case ISD::UDIV:               return visitUDIV(N);
1283   case ISD::SREM:               return visitSREM(N);
1284   case ISD::UREM:               return visitUREM(N);
1285   case ISD::MULHU:              return visitMULHU(N);
1286   case ISD::MULHS:              return visitMULHS(N);
1287   case ISD::SMUL_LOHI:          return visitSMUL_LOHI(N);
1288   case ISD::UMUL_LOHI:          return visitUMUL_LOHI(N);
1289   case ISD::SMULO:              return visitSMULO(N);
1290   case ISD::UMULO:              return visitUMULO(N);
1291   case ISD::SDIVREM:            return visitSDIVREM(N);
1292   case ISD::UDIVREM:            return visitUDIVREM(N);
1293   case ISD::AND:                return visitAND(N);
1294   case ISD::OR:                 return visitOR(N);
1295   case ISD::XOR:                return visitXOR(N);
1296   case ISD::SHL:                return visitSHL(N);
1297   case ISD::SRA:                return visitSRA(N);
1298   case ISD::SRL:                return visitSRL(N);
1299   case ISD::ROTR:
1300   case ISD::ROTL:               return visitRotate(N);
1301   case ISD::CTLZ:               return visitCTLZ(N);
1302   case ISD::CTLZ_ZERO_UNDEF:    return visitCTLZ_ZERO_UNDEF(N);
1303   case ISD::CTTZ:               return visitCTTZ(N);
1304   case ISD::CTTZ_ZERO_UNDEF:    return visitCTTZ_ZERO_UNDEF(N);
1305   case ISD::CTPOP:              return visitCTPOP(N);
1306   case ISD::SELECT:             return visitSELECT(N);
1307   case ISD::VSELECT:            return visitVSELECT(N);
1308   case ISD::SELECT_CC:          return visitSELECT_CC(N);
1309   case ISD::SETCC:              return visitSETCC(N);
1310   case ISD::SIGN_EXTEND:        return visitSIGN_EXTEND(N);
1311   case ISD::ZERO_EXTEND:        return visitZERO_EXTEND(N);
1312   case ISD::ANY_EXTEND:         return visitANY_EXTEND(N);
1313   case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
1314   case ISD::TRUNCATE:           return visitTRUNCATE(N);
1315   case ISD::BITCAST:            return visitBITCAST(N);
1316   case ISD::BUILD_PAIR:         return visitBUILD_PAIR(N);
1317   case ISD::FADD:               return visitFADD(N);
1318   case ISD::FSUB:               return visitFSUB(N);
1319   case ISD::FMUL:               return visitFMUL(N);
1320   case ISD::FMA:                return visitFMA(N);
1321   case ISD::FDIV:               return visitFDIV(N);
1322   case ISD::FREM:               return visitFREM(N);
1323   case ISD::FSQRT:              return visitFSQRT(N);
1324   case ISD::FCOPYSIGN:          return visitFCOPYSIGN(N);
1325   case ISD::SINT_TO_FP:         return visitSINT_TO_FP(N);
1326   case ISD::UINT_TO_FP:         return visitUINT_TO_FP(N);
1327   case ISD::FP_TO_SINT:         return visitFP_TO_SINT(N);
1328   case ISD::FP_TO_UINT:         return visitFP_TO_UINT(N);
1329   case ISD::FP_ROUND:           return visitFP_ROUND(N);
1330   case ISD::FP_ROUND_INREG:     return visitFP_ROUND_INREG(N);
1331   case ISD::FP_EXTEND:          return visitFP_EXTEND(N);
1332   case ISD::FNEG:               return visitFNEG(N);
1333   case ISD::FABS:               return visitFABS(N);
1334   case ISD::FFLOOR:             return visitFFLOOR(N);
1335   case ISD::FMINNUM:            return visitFMINNUM(N);
1336   case ISD::FMAXNUM:            return visitFMAXNUM(N);
1337   case ISD::FCEIL:              return visitFCEIL(N);
1338   case ISD::FTRUNC:             return visitFTRUNC(N);
1339   case ISD::BRCOND:             return visitBRCOND(N);
1340   case ISD::BR_CC:              return visitBR_CC(N);
1341   case ISD::LOAD:               return visitLOAD(N);
1342   case ISD::STORE:              return visitSTORE(N);
1343   case ISD::INSERT_VECTOR_ELT:  return visitINSERT_VECTOR_ELT(N);
1344   case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1345   case ISD::BUILD_VECTOR:       return visitBUILD_VECTOR(N);
1346   case ISD::CONCAT_VECTORS:     return visitCONCAT_VECTORS(N);
1347   case ISD::EXTRACT_SUBVECTOR:  return visitEXTRACT_SUBVECTOR(N);
1348   case ISD::VECTOR_SHUFFLE:     return visitVECTOR_SHUFFLE(N);
1349   case ISD::INSERT_SUBVECTOR:   return visitINSERT_SUBVECTOR(N);
1350   }
1351   return SDValue();
1352 }
1353
1354 SDValue DAGCombiner::combine(SDNode *N) {
1355   SDValue RV = visit(N);
1356
1357   // If nothing happened, try a target-specific DAG combine.
1358   if (!RV.getNode()) {
1359     assert(N->getOpcode() != ISD::DELETED_NODE &&
1360            "Node was deleted but visit returned NULL!");
1361
1362     if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1363         TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1364
1365       // Expose the DAG combiner to the target combiner impls.
1366       TargetLowering::DAGCombinerInfo
1367         DagCombineInfo(DAG, Level, false, this);
1368
1369       RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1370     }
1371   }
1372
1373   // If nothing happened still, try promoting the operation.
1374   if (!RV.getNode()) {
1375     switch (N->getOpcode()) {
1376     default: break;
1377     case ISD::ADD:
1378     case ISD::SUB:
1379     case ISD::MUL:
1380     case ISD::AND:
1381     case ISD::OR:
1382     case ISD::XOR:
1383       RV = PromoteIntBinOp(SDValue(N, 0));
1384       break;
1385     case ISD::SHL:
1386     case ISD::SRA:
1387     case ISD::SRL:
1388       RV = PromoteIntShiftOp(SDValue(N, 0));
1389       break;
1390     case ISD::SIGN_EXTEND:
1391     case ISD::ZERO_EXTEND:
1392     case ISD::ANY_EXTEND:
1393       RV = PromoteExtend(SDValue(N, 0));
1394       break;
1395     case ISD::LOAD:
1396       if (PromoteLoad(SDValue(N, 0)))
1397         RV = SDValue(N, 0);
1398       break;
1399     }
1400   }
1401
1402   // If N is a commutative binary node, try commuting it to enable more
1403   // sdisel CSE.
1404   if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1405       N->getNumValues() == 1) {
1406     SDValue N0 = N->getOperand(0);
1407     SDValue N1 = N->getOperand(1);
1408
1409     // Constant operands are canonicalized to RHS.
1410     if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1411       SDValue Ops[] = {N1, N0};
1412       SDNode *CSENode;
1413       if (const BinaryWithFlagsSDNode *BinNode =
1414               dyn_cast<BinaryWithFlagsSDNode>(N)) {
1415         CSENode = DAG.getNodeIfExists(
1416             N->getOpcode(), N->getVTList(), Ops, BinNode->hasNoUnsignedWrap(),
1417             BinNode->hasNoSignedWrap(), BinNode->isExact());
1418       } else {
1419         CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops);
1420       }
1421       if (CSENode)
1422         return SDValue(CSENode, 0);
1423     }
1424   }
1425
1426   return RV;
1427 }
1428
1429 /// Given a node, return its input chain if it has one, otherwise return a null
1430 /// sd operand.
1431 static SDValue getInputChainForNode(SDNode *N) {
1432   if (unsigned NumOps = N->getNumOperands()) {
1433     if (N->getOperand(0).getValueType() == MVT::Other)
1434       return N->getOperand(0);
1435     if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1436       return N->getOperand(NumOps-1);
1437     for (unsigned i = 1; i < NumOps-1; ++i)
1438       if (N->getOperand(i).getValueType() == MVT::Other)
1439         return N->getOperand(i);
1440   }
1441   return SDValue();
1442 }
1443
1444 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1445   // If N has two operands, where one has an input chain equal to the other,
1446   // the 'other' chain is redundant.
1447   if (N->getNumOperands() == 2) {
1448     if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1449       return N->getOperand(0);
1450     if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1451       return N->getOperand(1);
1452   }
1453
1454   SmallVector<SDNode *, 8> TFs;     // List of token factors to visit.
1455   SmallVector<SDValue, 8> Ops;    // Ops for replacing token factor.
1456   SmallPtrSet<SDNode*, 16> SeenOps;
1457   bool Changed = false;             // If we should replace this token factor.
1458
1459   // Start out with this token factor.
1460   TFs.push_back(N);
1461
1462   // Iterate through token factors.  The TFs grows when new token factors are
1463   // encountered.
1464   for (unsigned i = 0; i < TFs.size(); ++i) {
1465     SDNode *TF = TFs[i];
1466
1467     // Check each of the operands.
1468     for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1469       SDValue Op = TF->getOperand(i);
1470
1471       switch (Op.getOpcode()) {
1472       case ISD::EntryToken:
1473         // Entry tokens don't need to be added to the list. They are
1474         // rededundant.
1475         Changed = true;
1476         break;
1477
1478       case ISD::TokenFactor:
1479         if (Op.hasOneUse() &&
1480             std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1481           // Queue up for processing.
1482           TFs.push_back(Op.getNode());
1483           // Clean up in case the token factor is removed.
1484           AddToWorklist(Op.getNode());
1485           Changed = true;
1486           break;
1487         }
1488         // Fall thru
1489
1490       default:
1491         // Only add if it isn't already in the list.
1492         if (SeenOps.insert(Op.getNode()))
1493           Ops.push_back(Op);
1494         else
1495           Changed = true;
1496         break;
1497       }
1498     }
1499   }
1500
1501   SDValue Result;
1502
1503   // If we've change things around then replace token factor.
1504   if (Changed) {
1505     if (Ops.empty()) {
1506       // The entry token is the only possible outcome.
1507       Result = DAG.getEntryNode();
1508     } else {
1509       // New and improved token factor.
1510       Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1511     }
1512
1513     // Don't add users to work list.
1514     return CombineTo(N, Result, false);
1515   }
1516
1517   return Result;
1518 }
1519
1520 /// MERGE_VALUES can always be eliminated.
1521 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1522   WorklistRemover DeadNodes(*this);
1523   // Replacing results may cause a different MERGE_VALUES to suddenly
1524   // be CSE'd with N, and carry its uses with it. Iterate until no
1525   // uses remain, to ensure that the node can be safely deleted.
1526   // First add the users of this node to the work list so that they
1527   // can be tried again once they have new operands.
1528   AddUsersToWorklist(N);
1529   do {
1530     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1531       DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1532   } while (!N->use_empty());
1533   deleteAndRecombine(N);
1534   return SDValue(N, 0);   // Return N so it doesn't get rechecked!
1535 }
1536
1537 SDValue DAGCombiner::visitADD(SDNode *N) {
1538   SDValue N0 = N->getOperand(0);
1539   SDValue N1 = N->getOperand(1);
1540   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1541   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1542   EVT VT = N0.getValueType();
1543
1544   // fold vector ops
1545   if (VT.isVector()) {
1546     SDValue FoldedVOp = SimplifyVBinOp(N);
1547     if (FoldedVOp.getNode()) return FoldedVOp;
1548
1549     // fold (add x, 0) -> x, vector edition
1550     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1551       return N0;
1552     if (ISD::isBuildVectorAllZeros(N0.getNode()))
1553       return N1;
1554   }
1555
1556   // fold (add x, undef) -> undef
1557   if (N0.getOpcode() == ISD::UNDEF)
1558     return N0;
1559   if (N1.getOpcode() == ISD::UNDEF)
1560     return N1;
1561   // fold (add c1, c2) -> c1+c2
1562   if (N0C && N1C)
1563     return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
1564   // canonicalize constant to RHS
1565   if (N0C && !N1C)
1566     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1567   // fold (add x, 0) -> x
1568   if (N1C && N1C->isNullValue())
1569     return N0;
1570   // fold (add Sym, c) -> Sym+c
1571   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1572     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1573         GA->getOpcode() == ISD::GlobalAddress)
1574       return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1575                                   GA->getOffset() +
1576                                     (uint64_t)N1C->getSExtValue());
1577   // fold ((c1-A)+c2) -> (c1+c2)-A
1578   if (N1C && N0.getOpcode() == ISD::SUB)
1579     if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
1580       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1581                          DAG.getConstant(N1C->getAPIntValue()+
1582                                          N0C->getAPIntValue(), VT),
1583                          N0.getOperand(1));
1584   // reassociate add
1585   SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1);
1586   if (RADD.getNode())
1587     return RADD;
1588   // fold ((0-A) + B) -> B-A
1589   if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1590       cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1591     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1592   // fold (A + (0-B)) -> A-B
1593   if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1594       cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1595     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1596   // fold (A+(B-A)) -> B
1597   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1598     return N1.getOperand(0);
1599   // fold ((B-A)+A) -> B
1600   if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1601     return N0.getOperand(0);
1602   // fold (A+(B-(A+C))) to (B-C)
1603   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1604       N0 == N1.getOperand(1).getOperand(0))
1605     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1606                        N1.getOperand(1).getOperand(1));
1607   // fold (A+(B-(C+A))) to (B-C)
1608   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1609       N0 == N1.getOperand(1).getOperand(1))
1610     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1611                        N1.getOperand(1).getOperand(0));
1612   // fold (A+((B-A)+or-C)) to (B+or-C)
1613   if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1614       N1.getOperand(0).getOpcode() == ISD::SUB &&
1615       N0 == N1.getOperand(0).getOperand(1))
1616     return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1617                        N1.getOperand(0).getOperand(0), N1.getOperand(1));
1618
1619   // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1620   if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1621     SDValue N00 = N0.getOperand(0);
1622     SDValue N01 = N0.getOperand(1);
1623     SDValue N10 = N1.getOperand(0);
1624     SDValue N11 = N1.getOperand(1);
1625
1626     if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1627       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1628                          DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1629                          DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1630   }
1631
1632   if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1633     return SDValue(N, 0);
1634
1635   // fold (a+b) -> (a|b) iff a and b share no bits.
1636   if (VT.isInteger() && !VT.isVector()) {
1637     APInt LHSZero, LHSOne;
1638     APInt RHSZero, RHSOne;
1639     DAG.computeKnownBits(N0, LHSZero, LHSOne);
1640
1641     if (LHSZero.getBoolValue()) {
1642       DAG.computeKnownBits(N1, RHSZero, RHSOne);
1643
1644       // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1645       // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1646       if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1647         if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1648           return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1649       }
1650     }
1651   }
1652
1653   // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1654   if (N1.getOpcode() == ISD::SHL &&
1655       N1.getOperand(0).getOpcode() == ISD::SUB)
1656     if (ConstantSDNode *C =
1657           dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1658       if (C->getAPIntValue() == 0)
1659         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1660                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
1661                                        N1.getOperand(0).getOperand(1),
1662                                        N1.getOperand(1)));
1663   if (N0.getOpcode() == ISD::SHL &&
1664       N0.getOperand(0).getOpcode() == ISD::SUB)
1665     if (ConstantSDNode *C =
1666           dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1667       if (C->getAPIntValue() == 0)
1668         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1669                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
1670                                        N0.getOperand(0).getOperand(1),
1671                                        N0.getOperand(1)));
1672
1673   if (N1.getOpcode() == ISD::AND) {
1674     SDValue AndOp0 = N1.getOperand(0);
1675     ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1676     unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1677     unsigned DestBits = VT.getScalarType().getSizeInBits();
1678
1679     // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1680     // and similar xforms where the inner op is either ~0 or 0.
1681     if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1682       SDLoc DL(N);
1683       return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1684     }
1685   }
1686
1687   // add (sext i1), X -> sub X, (zext i1)
1688   if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1689       N0.getOperand(0).getValueType() == MVT::i1 &&
1690       !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1691     SDLoc DL(N);
1692     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1693     return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1694   }
1695
1696   // add X, (sextinreg Y i1) -> sub X, (and Y 1)
1697   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1698     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1699     if (TN->getVT() == MVT::i1) {
1700       SDLoc DL(N);
1701       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1702                                  DAG.getConstant(1, VT));
1703       return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
1704     }
1705   }
1706
1707   return SDValue();
1708 }
1709
1710 SDValue DAGCombiner::visitADDC(SDNode *N) {
1711   SDValue N0 = N->getOperand(0);
1712   SDValue N1 = N->getOperand(1);
1713   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1714   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1715   EVT VT = N0.getValueType();
1716
1717   // If the flag result is dead, turn this into an ADD.
1718   if (!N->hasAnyUseOfValue(1))
1719     return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1720                      DAG.getNode(ISD::CARRY_FALSE,
1721                                  SDLoc(N), MVT::Glue));
1722
1723   // canonicalize constant to RHS.
1724   if (N0C && !N1C)
1725     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1726
1727   // fold (addc x, 0) -> x + no carry out
1728   if (N1C && N1C->isNullValue())
1729     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1730                                         SDLoc(N), MVT::Glue));
1731
1732   // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1733   APInt LHSZero, LHSOne;
1734   APInt RHSZero, RHSOne;
1735   DAG.computeKnownBits(N0, LHSZero, LHSOne);
1736
1737   if (LHSZero.getBoolValue()) {
1738     DAG.computeKnownBits(N1, RHSZero, RHSOne);
1739
1740     // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1741     // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1742     if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1743       return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1744                        DAG.getNode(ISD::CARRY_FALSE,
1745                                    SDLoc(N), MVT::Glue));
1746   }
1747
1748   return SDValue();
1749 }
1750
1751 SDValue DAGCombiner::visitADDE(SDNode *N) {
1752   SDValue N0 = N->getOperand(0);
1753   SDValue N1 = N->getOperand(1);
1754   SDValue CarryIn = N->getOperand(2);
1755   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1756   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1757
1758   // canonicalize constant to RHS
1759   if (N0C && !N1C)
1760     return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1761                        N1, N0, CarryIn);
1762
1763   // fold (adde x, y, false) -> (addc x, y)
1764   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1765     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1766
1767   return SDValue();
1768 }
1769
1770 // Since it may not be valid to emit a fold to zero for vector initializers
1771 // check if we can before folding.
1772 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1773                              SelectionDAG &DAG,
1774                              bool LegalOperations, bool LegalTypes) {
1775   if (!VT.isVector())
1776     return DAG.getConstant(0, VT);
1777   if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1778     return DAG.getConstant(0, VT);
1779   return SDValue();
1780 }
1781
1782 SDValue DAGCombiner::visitSUB(SDNode *N) {
1783   SDValue N0 = N->getOperand(0);
1784   SDValue N1 = N->getOperand(1);
1785   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1786   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1787   ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1788     dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1789   EVT VT = N0.getValueType();
1790
1791   // fold vector ops
1792   if (VT.isVector()) {
1793     SDValue FoldedVOp = SimplifyVBinOp(N);
1794     if (FoldedVOp.getNode()) return FoldedVOp;
1795
1796     // fold (sub x, 0) -> x, vector edition
1797     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1798       return N0;
1799   }
1800
1801   // fold (sub x, x) -> 0
1802   // FIXME: Refactor this and xor and other similar operations together.
1803   if (N0 == N1)
1804     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1805   // fold (sub c1, c2) -> c1-c2
1806   if (N0C && N1C)
1807     return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1808   // fold (sub x, c) -> (add x, -c)
1809   if (N1C)
1810     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
1811                        DAG.getConstant(-N1C->getAPIntValue(), VT));
1812   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1813   if (N0C && N0C->isAllOnesValue())
1814     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1815   // fold A-(A-B) -> B
1816   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1817     return N1.getOperand(1);
1818   // fold (A+B)-A -> B
1819   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1820     return N0.getOperand(1);
1821   // fold (A+B)-B -> A
1822   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1823     return N0.getOperand(0);
1824   // fold C2-(A+C1) -> (C2-C1)-A
1825   if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1826     SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1827                                    VT);
1828     return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
1829                        N1.getOperand(0));
1830   }
1831   // fold ((A+(B+or-C))-B) -> A+or-C
1832   if (N0.getOpcode() == ISD::ADD &&
1833       (N0.getOperand(1).getOpcode() == ISD::SUB ||
1834        N0.getOperand(1).getOpcode() == ISD::ADD) &&
1835       N0.getOperand(1).getOperand(0) == N1)
1836     return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1837                        N0.getOperand(0), N0.getOperand(1).getOperand(1));
1838   // fold ((A+(C+B))-B) -> A+C
1839   if (N0.getOpcode() == ISD::ADD &&
1840       N0.getOperand(1).getOpcode() == ISD::ADD &&
1841       N0.getOperand(1).getOperand(1) == N1)
1842     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1843                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1844   // fold ((A-(B-C))-C) -> A-B
1845   if (N0.getOpcode() == ISD::SUB &&
1846       N0.getOperand(1).getOpcode() == ISD::SUB &&
1847       N0.getOperand(1).getOperand(1) == N1)
1848     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1849                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1850
1851   // If either operand of a sub is undef, the result is undef
1852   if (N0.getOpcode() == ISD::UNDEF)
1853     return N0;
1854   if (N1.getOpcode() == ISD::UNDEF)
1855     return N1;
1856
1857   // If the relocation model supports it, consider symbol offsets.
1858   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1859     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1860       // fold (sub Sym, c) -> Sym-c
1861       if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1862         return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1863                                     GA->getOffset() -
1864                                       (uint64_t)N1C->getSExtValue());
1865       // fold (sub Sym+c1, Sym+c2) -> c1-c2
1866       if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1867         if (GA->getGlobal() == GB->getGlobal())
1868           return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1869                                  VT);
1870     }
1871
1872   // sub X, (sextinreg Y i1) -> add X, (and Y 1)
1873   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1874     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1875     if (TN->getVT() == MVT::i1) {
1876       SDLoc DL(N);
1877       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1878                                  DAG.getConstant(1, VT));
1879       return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
1880     }
1881   }
1882
1883   return SDValue();
1884 }
1885
1886 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1887   SDValue N0 = N->getOperand(0);
1888   SDValue N1 = N->getOperand(1);
1889   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1890   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1891   EVT VT = N0.getValueType();
1892
1893   // If the flag result is dead, turn this into an SUB.
1894   if (!N->hasAnyUseOfValue(1))
1895     return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1896                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1897                                  MVT::Glue));
1898
1899   // fold (subc x, x) -> 0 + no borrow
1900   if (N0 == N1)
1901     return CombineTo(N, DAG.getConstant(0, VT),
1902                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1903                                  MVT::Glue));
1904
1905   // fold (subc x, 0) -> x + no borrow
1906   if (N1C && N1C->isNullValue())
1907     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1908                                         MVT::Glue));
1909
1910   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1911   if (N0C && N0C->isAllOnesValue())
1912     return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1913                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1914                                  MVT::Glue));
1915
1916   return SDValue();
1917 }
1918
1919 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1920   SDValue N0 = N->getOperand(0);
1921   SDValue N1 = N->getOperand(1);
1922   SDValue CarryIn = N->getOperand(2);
1923
1924   // fold (sube x, y, false) -> (subc x, y)
1925   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1926     return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
1927
1928   return SDValue();
1929 }
1930
1931 SDValue DAGCombiner::visitMUL(SDNode *N) {
1932   SDValue N0 = N->getOperand(0);
1933   SDValue N1 = N->getOperand(1);
1934   EVT VT = N0.getValueType();
1935
1936   // fold (mul x, undef) -> 0
1937   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1938     return DAG.getConstant(0, VT);
1939
1940   bool N0IsConst = false;
1941   bool N1IsConst = false;
1942   APInt ConstValue0, ConstValue1;
1943   // fold vector ops
1944   if (VT.isVector()) {
1945     SDValue FoldedVOp = SimplifyVBinOp(N);
1946     if (FoldedVOp.getNode()) return FoldedVOp;
1947
1948     N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1949     N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1950   } else {
1951     N0IsConst = dyn_cast<ConstantSDNode>(N0) != nullptr;
1952     ConstValue0 = N0IsConst ? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue()
1953                             : APInt();
1954     N1IsConst = dyn_cast<ConstantSDNode>(N1) != nullptr;
1955     ConstValue1 = N1IsConst ? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue()
1956                             : APInt();
1957   }
1958
1959   // fold (mul c1, c2) -> c1*c2
1960   if (N0IsConst && N1IsConst)
1961     return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
1962
1963   // canonicalize constant to RHS
1964   if (N0IsConst && !N1IsConst)
1965     return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
1966   // fold (mul x, 0) -> 0
1967   if (N1IsConst && ConstValue1 == 0)
1968     return N1;
1969   // We require a splat of the entire scalar bit width for non-contiguous
1970   // bit patterns.
1971   bool IsFullSplat =
1972     ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
1973   // fold (mul x, 1) -> x
1974   if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
1975     return N0;
1976   // fold (mul x, -1) -> 0-x
1977   if (N1IsConst && ConstValue1.isAllOnesValue())
1978     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1979                        DAG.getConstant(0, VT), N0);
1980   // fold (mul x, (1 << c)) -> x << c
1981   if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat)
1982     return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1983                        DAG.getConstant(ConstValue1.logBase2(),
1984                                        getShiftAmountTy(N0.getValueType())));
1985   // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1986   if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
1987     unsigned Log2Val = (-ConstValue1).logBase2();
1988     // FIXME: If the input is something that is easily negated (e.g. a
1989     // single-use add), we should put the negate there.
1990     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1991                        DAG.getConstant(0, VT),
1992                        DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1993                             DAG.getConstant(Log2Val,
1994                                       getShiftAmountTy(N0.getValueType()))));
1995   }
1996
1997   APInt Val;
1998   // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
1999   if (N1IsConst && N0.getOpcode() == ISD::SHL &&
2000       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2001                      isa<ConstantSDNode>(N0.getOperand(1)))) {
2002     SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
2003                              N1, N0.getOperand(1));
2004     AddToWorklist(C3.getNode());
2005     return DAG.getNode(ISD::MUL, SDLoc(N), VT,
2006                        N0.getOperand(0), C3);
2007   }
2008
2009   // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2010   // use.
2011   {
2012     SDValue Sh(nullptr,0), Y(nullptr,0);
2013     // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
2014     if (N0.getOpcode() == ISD::SHL &&
2015         (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2016                        isa<ConstantSDNode>(N0.getOperand(1))) &&
2017         N0.getNode()->hasOneUse()) {
2018       Sh = N0; Y = N1;
2019     } else if (N1.getOpcode() == ISD::SHL &&
2020                isa<ConstantSDNode>(N1.getOperand(1)) &&
2021                N1.getNode()->hasOneUse()) {
2022       Sh = N1; Y = N0;
2023     }
2024
2025     if (Sh.getNode()) {
2026       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2027                                 Sh.getOperand(0), Y);
2028       return DAG.getNode(ISD::SHL, SDLoc(N), VT,
2029                          Mul, Sh.getOperand(1));
2030     }
2031   }
2032
2033   // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2034   if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
2035       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2036                      isa<ConstantSDNode>(N0.getOperand(1))))
2037     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2038                        DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2039                                    N0.getOperand(0), N1),
2040                        DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2041                                    N0.getOperand(1), N1));
2042
2043   // reassociate mul
2044   SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1);
2045   if (RMUL.getNode())
2046     return RMUL;
2047
2048   return SDValue();
2049 }
2050
2051 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2052   SDValue N0 = N->getOperand(0);
2053   SDValue N1 = N->getOperand(1);
2054   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2055   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2056   EVT VT = N->getValueType(0);
2057
2058   // fold vector ops
2059   if (VT.isVector()) {
2060     SDValue FoldedVOp = SimplifyVBinOp(N);
2061     if (FoldedVOp.getNode()) return FoldedVOp;
2062   }
2063
2064   // fold (sdiv c1, c2) -> c1/c2
2065   if (N0C && N1C && !N1C->isNullValue())
2066     return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
2067   // fold (sdiv X, 1) -> X
2068   if (N1C && N1C->getAPIntValue() == 1LL)
2069     return N0;
2070   // fold (sdiv X, -1) -> 0-X
2071   if (N1C && N1C->isAllOnesValue())
2072     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
2073                        DAG.getConstant(0, VT), N0);
2074   // If we know the sign bits of both operands are zero, strength reduce to a
2075   // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
2076   if (!VT.isVector()) {
2077     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2078       return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
2079                          N0, N1);
2080   }
2081
2082   // fold (sdiv X, pow2) -> simple ops after legalize
2083   if (N1C && !N1C->isNullValue() && (N1C->getAPIntValue().isPowerOf2() ||
2084                                      (-N1C->getAPIntValue()).isPowerOf2())) {
2085     // If dividing by powers of two is cheap, then don't perform the following
2086     // fold.
2087     if (TLI.isPow2SDivCheap())
2088       return SDValue();
2089
2090     // Target-specific implementation of sdiv x, pow2.
2091     SDValue Res = BuildSDIVPow2(N);
2092     if (Res.getNode())
2093       return Res;
2094
2095     unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2096
2097     // Splat the sign bit into the register
2098     SDValue SGN =
2099         DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
2100                     DAG.getConstant(VT.getScalarSizeInBits() - 1,
2101                                     getShiftAmountTy(N0.getValueType())));
2102     AddToWorklist(SGN.getNode());
2103
2104     // Add (N0 < 0) ? abs2 - 1 : 0;
2105     SDValue SRL =
2106         DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
2107                     DAG.getConstant(VT.getScalarSizeInBits() - lg2,
2108                                     getShiftAmountTy(SGN.getValueType())));
2109     SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
2110     AddToWorklist(SRL.getNode());
2111     AddToWorklist(ADD.getNode());    // Divide by pow2
2112     SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
2113                   DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
2114
2115     // If we're dividing by a positive value, we're done.  Otherwise, we must
2116     // negate the result.
2117     if (N1C->getAPIntValue().isNonNegative())
2118       return SRA;
2119
2120     AddToWorklist(SRA.getNode());
2121     return DAG.getNode(ISD::SUB, SDLoc(N), VT, DAG.getConstant(0, VT), SRA);
2122   }
2123
2124   // if integer divide is expensive and we satisfy the requirements, emit an
2125   // alternate sequence.
2126   if (N1C && !TLI.isIntDivCheap()) {
2127     SDValue Op = BuildSDIV(N);
2128     if (Op.getNode()) return Op;
2129   }
2130
2131   // undef / X -> 0
2132   if (N0.getOpcode() == ISD::UNDEF)
2133     return DAG.getConstant(0, VT);
2134   // X / undef -> undef
2135   if (N1.getOpcode() == ISD::UNDEF)
2136     return N1;
2137
2138   return SDValue();
2139 }
2140
2141 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2142   SDValue N0 = N->getOperand(0);
2143   SDValue N1 = N->getOperand(1);
2144   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2145   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2146   EVT VT = N->getValueType(0);
2147
2148   // fold vector ops
2149   if (VT.isVector()) {
2150     SDValue FoldedVOp = SimplifyVBinOp(N);
2151     if (FoldedVOp.getNode()) return FoldedVOp;
2152   }
2153
2154   // fold (udiv c1, c2) -> c1/c2
2155   if (N0C && N1C && !N1C->isNullValue())
2156     return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
2157   // fold (udiv x, (1 << c)) -> x >>u c
2158   if (N1C && N1C->getAPIntValue().isPowerOf2())
2159     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
2160                        DAG.getConstant(N1C->getAPIntValue().logBase2(),
2161                                        getShiftAmountTy(N0.getValueType())));
2162   // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2163   if (N1.getOpcode() == ISD::SHL) {
2164     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2165       if (SHC->getAPIntValue().isPowerOf2()) {
2166         EVT ADDVT = N1.getOperand(1).getValueType();
2167         SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
2168                                   N1.getOperand(1),
2169                                   DAG.getConstant(SHC->getAPIntValue()
2170                                                                   .logBase2(),
2171                                                   ADDVT));
2172         AddToWorklist(Add.getNode());
2173         return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
2174       }
2175     }
2176   }
2177   // fold (udiv x, c) -> alternate
2178   if (N1C && !TLI.isIntDivCheap()) {
2179     SDValue Op = BuildUDIV(N);
2180     if (Op.getNode()) return Op;
2181   }
2182
2183   // undef / X -> 0
2184   if (N0.getOpcode() == ISD::UNDEF)
2185     return DAG.getConstant(0, VT);
2186   // X / undef -> undef
2187   if (N1.getOpcode() == ISD::UNDEF)
2188     return N1;
2189
2190   return SDValue();
2191 }
2192
2193 SDValue DAGCombiner::visitSREM(SDNode *N) {
2194   SDValue N0 = N->getOperand(0);
2195   SDValue N1 = N->getOperand(1);
2196   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2197   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2198   EVT VT = N->getValueType(0);
2199
2200   // fold (srem c1, c2) -> c1%c2
2201   if (N0C && N1C && !N1C->isNullValue())
2202     return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
2203   // If we know the sign bits of both operands are zero, strength reduce to a
2204   // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2205   if (!VT.isVector()) {
2206     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2207       return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2208   }
2209
2210   // If X/C can be simplified by the division-by-constant logic, lower
2211   // X%C to the equivalent of X-X/C*C.
2212   if (N1C && !N1C->isNullValue()) {
2213     SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2214     AddToWorklist(Div.getNode());
2215     SDValue OptimizedDiv = combine(Div.getNode());
2216     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2217       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2218                                 OptimizedDiv, N1);
2219       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2220       AddToWorklist(Mul.getNode());
2221       return Sub;
2222     }
2223   }
2224
2225   // undef % X -> 0
2226   if (N0.getOpcode() == ISD::UNDEF)
2227     return DAG.getConstant(0, VT);
2228   // X % undef -> undef
2229   if (N1.getOpcode() == ISD::UNDEF)
2230     return N1;
2231
2232   return SDValue();
2233 }
2234
2235 SDValue DAGCombiner::visitUREM(SDNode *N) {
2236   SDValue N0 = N->getOperand(0);
2237   SDValue N1 = N->getOperand(1);
2238   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2239   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2240   EVT VT = N->getValueType(0);
2241
2242   // fold (urem c1, c2) -> c1%c2
2243   if (N0C && N1C && !N1C->isNullValue())
2244     return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
2245   // fold (urem x, pow2) -> (and x, pow2-1)
2246   if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
2247     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
2248                        DAG.getConstant(N1C->getAPIntValue()-1,VT));
2249   // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2250   if (N1.getOpcode() == ISD::SHL) {
2251     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2252       if (SHC->getAPIntValue().isPowerOf2()) {
2253         SDValue Add =
2254           DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
2255                  DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
2256                                  VT));
2257         AddToWorklist(Add.getNode());
2258         return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
2259       }
2260     }
2261   }
2262
2263   // If X/C can be simplified by the division-by-constant logic, lower
2264   // X%C to the equivalent of X-X/C*C.
2265   if (N1C && !N1C->isNullValue()) {
2266     SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2267     AddToWorklist(Div.getNode());
2268     SDValue OptimizedDiv = combine(Div.getNode());
2269     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2270       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2271                                 OptimizedDiv, N1);
2272       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2273       AddToWorklist(Mul.getNode());
2274       return Sub;
2275     }
2276   }
2277
2278   // undef % X -> 0
2279   if (N0.getOpcode() == ISD::UNDEF)
2280     return DAG.getConstant(0, VT);
2281   // X % undef -> undef
2282   if (N1.getOpcode() == ISD::UNDEF)
2283     return N1;
2284
2285   return SDValue();
2286 }
2287
2288 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2289   SDValue N0 = N->getOperand(0);
2290   SDValue N1 = N->getOperand(1);
2291   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2292   EVT VT = N->getValueType(0);
2293   SDLoc DL(N);
2294
2295   // fold (mulhs x, 0) -> 0
2296   if (N1C && N1C->isNullValue())
2297     return N1;
2298   // fold (mulhs x, 1) -> (sra x, size(x)-1)
2299   if (N1C && N1C->getAPIntValue() == 1)
2300     return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
2301                        DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2302                                        getShiftAmountTy(N0.getValueType())));
2303   // fold (mulhs x, undef) -> 0
2304   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2305     return DAG.getConstant(0, VT);
2306
2307   // If the type twice as wide is legal, transform the mulhs to a wider multiply
2308   // plus a shift.
2309   if (VT.isSimple() && !VT.isVector()) {
2310     MVT Simple = VT.getSimpleVT();
2311     unsigned SimpleSize = Simple.getSizeInBits();
2312     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2313     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2314       N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2315       N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2316       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2317       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2318             DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2319       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2320     }
2321   }
2322
2323   return SDValue();
2324 }
2325
2326 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2327   SDValue N0 = N->getOperand(0);
2328   SDValue N1 = N->getOperand(1);
2329   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2330   EVT VT = N->getValueType(0);
2331   SDLoc DL(N);
2332
2333   // fold (mulhu x, 0) -> 0
2334   if (N1C && N1C->isNullValue())
2335     return N1;
2336   // fold (mulhu x, 1) -> 0
2337   if (N1C && N1C->getAPIntValue() == 1)
2338     return DAG.getConstant(0, N0.getValueType());
2339   // fold (mulhu x, undef) -> 0
2340   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2341     return DAG.getConstant(0, VT);
2342
2343   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2344   // plus a shift.
2345   if (VT.isSimple() && !VT.isVector()) {
2346     MVT Simple = VT.getSimpleVT();
2347     unsigned SimpleSize = Simple.getSizeInBits();
2348     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2349     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2350       N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2351       N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2352       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2353       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2354             DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2355       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2356     }
2357   }
2358
2359   return SDValue();
2360 }
2361
2362 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
2363 /// give the opcodes for the two computations that are being performed. Return
2364 /// true if a simplification was made.
2365 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2366                                                 unsigned HiOp) {
2367   // If the high half is not needed, just compute the low half.
2368   bool HiExists = N->hasAnyUseOfValue(1);
2369   if (!HiExists &&
2370       (!LegalOperations ||
2371        TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2372     SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2373     return CombineTo(N, Res, Res);
2374   }
2375
2376   // If the low half is not needed, just compute the high half.
2377   bool LoExists = N->hasAnyUseOfValue(0);
2378   if (!LoExists &&
2379       (!LegalOperations ||
2380        TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2381     SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2382     return CombineTo(N, Res, Res);
2383   }
2384
2385   // If both halves are used, return as it is.
2386   if (LoExists && HiExists)
2387     return SDValue();
2388
2389   // If the two computed results can be simplified separately, separate them.
2390   if (LoExists) {
2391     SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2392     AddToWorklist(Lo.getNode());
2393     SDValue LoOpt = combine(Lo.getNode());
2394     if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2395         (!LegalOperations ||
2396          TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2397       return CombineTo(N, LoOpt, LoOpt);
2398   }
2399
2400   if (HiExists) {
2401     SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2402     AddToWorklist(Hi.getNode());
2403     SDValue HiOpt = combine(Hi.getNode());
2404     if (HiOpt.getNode() && HiOpt != Hi &&
2405         (!LegalOperations ||
2406          TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2407       return CombineTo(N, HiOpt, HiOpt);
2408   }
2409
2410   return SDValue();
2411 }
2412
2413 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2414   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2415   if (Res.getNode()) return Res;
2416
2417   EVT VT = N->getValueType(0);
2418   SDLoc DL(N);
2419
2420   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2421   // plus a shift.
2422   if (VT.isSimple() && !VT.isVector()) {
2423     MVT Simple = VT.getSimpleVT();
2424     unsigned SimpleSize = Simple.getSizeInBits();
2425     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2426     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2427       SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2428       SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2429       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2430       // Compute the high part as N1.
2431       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2432             DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2433       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2434       // Compute the low part as N0.
2435       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2436       return CombineTo(N, Lo, Hi);
2437     }
2438   }
2439
2440   return SDValue();
2441 }
2442
2443 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2444   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2445   if (Res.getNode()) return Res;
2446
2447   EVT VT = N->getValueType(0);
2448   SDLoc DL(N);
2449
2450   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2451   // plus a shift.
2452   if (VT.isSimple() && !VT.isVector()) {
2453     MVT Simple = VT.getSimpleVT();
2454     unsigned SimpleSize = Simple.getSizeInBits();
2455     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2456     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2457       SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2458       SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2459       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2460       // Compute the high part as N1.
2461       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2462             DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2463       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2464       // Compute the low part as N0.
2465       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2466       return CombineTo(N, Lo, Hi);
2467     }
2468   }
2469
2470   return SDValue();
2471 }
2472
2473 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2474   // (smulo x, 2) -> (saddo x, x)
2475   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2476     if (C2->getAPIntValue() == 2)
2477       return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2478                          N->getOperand(0), N->getOperand(0));
2479
2480   return SDValue();
2481 }
2482
2483 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2484   // (umulo x, 2) -> (uaddo x, x)
2485   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2486     if (C2->getAPIntValue() == 2)
2487       return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2488                          N->getOperand(0), N->getOperand(0));
2489
2490   return SDValue();
2491 }
2492
2493 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2494   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2495   if (Res.getNode()) return Res;
2496
2497   return SDValue();
2498 }
2499
2500 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2501   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2502   if (Res.getNode()) return Res;
2503
2504   return SDValue();
2505 }
2506
2507 /// If this is a binary operator with two operands of the same opcode, try to
2508 /// simplify it.
2509 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2510   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2511   EVT VT = N0.getValueType();
2512   assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2513
2514   // Bail early if none of these transforms apply.
2515   if (N0.getNode()->getNumOperands() == 0) return SDValue();
2516
2517   // For each of OP in AND/OR/XOR:
2518   // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2519   // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2520   // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2521   // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2522   //
2523   // do not sink logical op inside of a vector extend, since it may combine
2524   // into a vsetcc.
2525   EVT Op0VT = N0.getOperand(0).getValueType();
2526   if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2527        N0.getOpcode() == ISD::SIGN_EXTEND ||
2528        // Avoid infinite looping with PromoteIntBinOp.
2529        (N0.getOpcode() == ISD::ANY_EXTEND &&
2530         (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2531        (N0.getOpcode() == ISD::TRUNCATE &&
2532         (!TLI.isZExtFree(VT, Op0VT) ||
2533          !TLI.isTruncateFree(Op0VT, VT)) &&
2534         TLI.isTypeLegal(Op0VT))) &&
2535       !VT.isVector() &&
2536       Op0VT == N1.getOperand(0).getValueType() &&
2537       (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2538     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2539                                  N0.getOperand(0).getValueType(),
2540                                  N0.getOperand(0), N1.getOperand(0));
2541     AddToWorklist(ORNode.getNode());
2542     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2543   }
2544
2545   // For each of OP in SHL/SRL/SRA/AND...
2546   //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2547   //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
2548   //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2549   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2550        N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2551       N0.getOperand(1) == N1.getOperand(1)) {
2552     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2553                                  N0.getOperand(0).getValueType(),
2554                                  N0.getOperand(0), N1.getOperand(0));
2555     AddToWorklist(ORNode.getNode());
2556     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2557                        ORNode, N0.getOperand(1));
2558   }
2559
2560   // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2561   // Only perform this optimization after type legalization and before
2562   // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2563   // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2564   // we don't want to undo this promotion.
2565   // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2566   // on scalars.
2567   if ((N0.getOpcode() == ISD::BITCAST ||
2568        N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2569       Level == AfterLegalizeTypes) {
2570     SDValue In0 = N0.getOperand(0);
2571     SDValue In1 = N1.getOperand(0);
2572     EVT In0Ty = In0.getValueType();
2573     EVT In1Ty = In1.getValueType();
2574     SDLoc DL(N);
2575     // If both incoming values are integers, and the original types are the
2576     // same.
2577     if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2578       SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2579       SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2580       AddToWorklist(Op.getNode());
2581       return BC;
2582     }
2583   }
2584
2585   // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2586   // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2587   // If both shuffles use the same mask, and both shuffle within a single
2588   // vector, then it is worthwhile to move the swizzle after the operation.
2589   // The type-legalizer generates this pattern when loading illegal
2590   // vector types from memory. In many cases this allows additional shuffle
2591   // optimizations.
2592   // There are other cases where moving the shuffle after the xor/and/or
2593   // is profitable even if shuffles don't perform a swizzle.
2594   // If both shuffles use the same mask, and both shuffles have the same first
2595   // or second operand, then it might still be profitable to move the shuffle
2596   // after the xor/and/or operation.
2597   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2598     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2599     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2600
2601     assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2602            "Inputs to shuffles are not the same type");
2603
2604     // Check that both shuffles use the same mask. The masks are known to be of
2605     // the same length because the result vector type is the same.
2606     // Check also that shuffles have only one use to avoid introducing extra
2607     // instructions.
2608     if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2609         SVN0->getMask().equals(SVN1->getMask())) {
2610       SDValue ShOp = N0->getOperand(1);
2611
2612       // Don't try to fold this node if it requires introducing a
2613       // build vector of all zeros that might be illegal at this stage.
2614       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2615         if (!LegalTypes)
2616           ShOp = DAG.getConstant(0, VT);
2617         else
2618           ShOp = SDValue();
2619       }
2620
2621       // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2622       // (OR  (shuf (A, C), shuf (B, C)) -> shuf (OR  (A, B), C)
2623       // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2624       if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2625         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2626                                       N0->getOperand(0), N1->getOperand(0));
2627         AddToWorklist(NewNode.getNode());
2628         return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2629                                     &SVN0->getMask()[0]);
2630       }
2631
2632       // Don't try to fold this node if it requires introducing a
2633       // build vector of all zeros that might be illegal at this stage.
2634       ShOp = N0->getOperand(0);
2635       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2636         if (!LegalTypes)
2637           ShOp = DAG.getConstant(0, VT);
2638         else
2639           ShOp = SDValue();
2640       }
2641
2642       // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2643       // (OR  (shuf (C, A), shuf (C, B)) -> shuf (C, OR  (A, B))
2644       // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2645       if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2646         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2647                                       N0->getOperand(1), N1->getOperand(1));
2648         AddToWorklist(NewNode.getNode());
2649         return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2650                                     &SVN0->getMask()[0]);
2651       }
2652     }
2653   }
2654
2655   return SDValue();
2656 }
2657
2658 SDValue DAGCombiner::visitAND(SDNode *N) {
2659   SDValue N0 = N->getOperand(0);
2660   SDValue N1 = N->getOperand(1);
2661   SDValue LL, LR, RL, RR, CC0, CC1;
2662   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2663   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2664   EVT VT = N1.getValueType();
2665   unsigned BitWidth = VT.getScalarType().getSizeInBits();
2666
2667   // fold vector ops
2668   if (VT.isVector()) {
2669     SDValue FoldedVOp = SimplifyVBinOp(N);
2670     if (FoldedVOp.getNode()) return FoldedVOp;
2671
2672     // fold (and x, 0) -> 0, vector edition
2673     if (ISD::isBuildVectorAllZeros(N0.getNode()))
2674       // do not return N0, because undef node may exist in N0
2675       return DAG.getConstant(
2676           APInt::getNullValue(
2677               N0.getValueType().getScalarType().getSizeInBits()),
2678           N0.getValueType());
2679     if (ISD::isBuildVectorAllZeros(N1.getNode()))
2680       // do not return N1, because undef node may exist in N1
2681       return DAG.getConstant(
2682           APInt::getNullValue(
2683               N1.getValueType().getScalarType().getSizeInBits()),
2684           N1.getValueType());
2685
2686     // fold (and x, -1) -> x, vector edition
2687     if (ISD::isBuildVectorAllOnes(N0.getNode()))
2688       return N1;
2689     if (ISD::isBuildVectorAllOnes(N1.getNode()))
2690       return N0;
2691   }
2692
2693   // fold (and x, undef) -> 0
2694   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2695     return DAG.getConstant(0, VT);
2696   // fold (and c1, c2) -> c1&c2
2697   if (N0C && N1C)
2698     return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
2699   // canonicalize constant to RHS
2700   if (N0C && !N1C)
2701     return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2702   // fold (and x, -1) -> x
2703   if (N1C && N1C->isAllOnesValue())
2704     return N0;
2705   // if (and x, c) is known to be zero, return 0
2706   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2707                                    APInt::getAllOnesValue(BitWidth)))
2708     return DAG.getConstant(0, VT);
2709   // reassociate and
2710   SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1);
2711   if (RAND.getNode())
2712     return RAND;
2713   // fold (and (or x, C), D) -> D if (C & D) == D
2714   if (N1C && N0.getOpcode() == ISD::OR)
2715     if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2716       if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2717         return N1;
2718   // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2719   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2720     SDValue N0Op0 = N0.getOperand(0);
2721     APInt Mask = ~N1C->getAPIntValue();
2722     Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2723     if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2724       SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2725                                  N0.getValueType(), N0Op0);
2726
2727       // Replace uses of the AND with uses of the Zero extend node.
2728       CombineTo(N, Zext);
2729
2730       // We actually want to replace all uses of the any_extend with the
2731       // zero_extend, to avoid duplicating things.  This will later cause this
2732       // AND to be folded.
2733       CombineTo(N0.getNode(), Zext);
2734       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2735     }
2736   }
2737   // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2738   // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2739   // already be zero by virtue of the width of the base type of the load.
2740   //
2741   // the 'X' node here can either be nothing or an extract_vector_elt to catch
2742   // more cases.
2743   if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2744        N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2745       N0.getOpcode() == ISD::LOAD) {
2746     LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2747                                          N0 : N0.getOperand(0) );
2748
2749     // Get the constant (if applicable) the zero'th operand is being ANDed with.
2750     // This can be a pure constant or a vector splat, in which case we treat the
2751     // vector as a scalar and use the splat value.
2752     APInt Constant = APInt::getNullValue(1);
2753     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2754       Constant = C->getAPIntValue();
2755     } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2756       APInt SplatValue, SplatUndef;
2757       unsigned SplatBitSize;
2758       bool HasAnyUndefs;
2759       bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2760                                              SplatBitSize, HasAnyUndefs);
2761       if (IsSplat) {
2762         // Undef bits can contribute to a possible optimisation if set, so
2763         // set them.
2764         SplatValue |= SplatUndef;
2765
2766         // The splat value may be something like "0x00FFFFFF", which means 0 for
2767         // the first vector value and FF for the rest, repeating. We need a mask
2768         // that will apply equally to all members of the vector, so AND all the
2769         // lanes of the constant together.
2770         EVT VT = Vector->getValueType(0);
2771         unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2772
2773         // If the splat value has been compressed to a bitlength lower
2774         // than the size of the vector lane, we need to re-expand it to
2775         // the lane size.
2776         if (BitWidth > SplatBitSize)
2777           for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2778                SplatBitSize < BitWidth;
2779                SplatBitSize = SplatBitSize * 2)
2780             SplatValue |= SplatValue.shl(SplatBitSize);
2781
2782         Constant = APInt::getAllOnesValue(BitWidth);
2783         for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2784           Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2785       }
2786     }
2787
2788     // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2789     // actually legal and isn't going to get expanded, else this is a false
2790     // optimisation.
2791     bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2792                                                     Load->getMemoryVT());
2793
2794     // Resize the constant to the same size as the original memory access before
2795     // extension. If it is still the AllOnesValue then this AND is completely
2796     // unneeded.
2797     Constant =
2798       Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2799
2800     bool B;
2801     switch (Load->getExtensionType()) {
2802     default: B = false; break;
2803     case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2804     case ISD::ZEXTLOAD:
2805     case ISD::NON_EXTLOAD: B = true; break;
2806     }
2807
2808     if (B && Constant.isAllOnesValue()) {
2809       // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2810       // preserve semantics once we get rid of the AND.
2811       SDValue NewLoad(Load, 0);
2812       if (Load->getExtensionType() == ISD::EXTLOAD) {
2813         NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
2814                               Load->getValueType(0), SDLoc(Load),
2815                               Load->getChain(), Load->getBasePtr(),
2816                               Load->getOffset(), Load->getMemoryVT(),
2817                               Load->getMemOperand());
2818         // Replace uses of the EXTLOAD with the new ZEXTLOAD.
2819         if (Load->getNumValues() == 3) {
2820           // PRE/POST_INC loads have 3 values.
2821           SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2822                            NewLoad.getValue(2) };
2823           CombineTo(Load, To, 3, true);
2824         } else {
2825           CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2826         }
2827       }
2828
2829       // Fold the AND away, taking care not to fold to the old load node if we
2830       // replaced it.
2831       CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2832
2833       return SDValue(N, 0); // Return N so it doesn't get rechecked!
2834     }
2835   }
2836   // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2837   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2838     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2839     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2840
2841     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2842         LL.getValueType().isInteger()) {
2843       // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2844       if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2845         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2846                                      LR.getValueType(), LL, RL);
2847         AddToWorklist(ORNode.getNode());
2848         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2849       }
2850       // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2851       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2852         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2853                                       LR.getValueType(), LL, RL);
2854         AddToWorklist(ANDNode.getNode());
2855         return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
2856       }
2857       // fold (and (setgt X,  -1), (setgt Y,  -1)) -> (setgt (or X, Y), -1)
2858       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2859         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2860                                      LR.getValueType(), LL, RL);
2861         AddToWorklist(ORNode.getNode());
2862         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2863       }
2864     }
2865     // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2866     if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2867         Op0 == Op1 && LL.getValueType().isInteger() &&
2868       Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2869                                  cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2870                                 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2871                                  cast<ConstantSDNode>(RR)->isNullValue()))) {
2872       SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(),
2873                                     LL, DAG.getConstant(1, LL.getValueType()));
2874       AddToWorklist(ADDNode.getNode());
2875       return DAG.getSetCC(SDLoc(N), VT, ADDNode,
2876                           DAG.getConstant(2, LL.getValueType()), ISD::SETUGE);
2877     }
2878     // canonicalize equivalent to ll == rl
2879     if (LL == RR && LR == RL) {
2880       Op1 = ISD::getSetCCSwappedOperands(Op1);
2881       std::swap(RL, RR);
2882     }
2883     if (LL == RL && LR == RR) {
2884       bool isInteger = LL.getValueType().isInteger();
2885       ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2886       if (Result != ISD::SETCC_INVALID &&
2887           (!LegalOperations ||
2888            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2889             TLI.isOperationLegal(ISD::SETCC,
2890                             getSetCCResultType(N0.getSimpleValueType())))))
2891         return DAG.getSetCC(SDLoc(N), N0.getValueType(),
2892                             LL, LR, Result);
2893     }
2894   }
2895
2896   // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
2897   if (N0.getOpcode() == N1.getOpcode()) {
2898     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2899     if (Tmp.getNode()) return Tmp;
2900   }
2901
2902   // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2903   // fold (and (sra)) -> (and (srl)) when possible.
2904   if (!VT.isVector() &&
2905       SimplifyDemandedBits(SDValue(N, 0)))
2906     return SDValue(N, 0);
2907
2908   // fold (zext_inreg (extload x)) -> (zextload x)
2909   if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
2910     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2911     EVT MemVT = LN0->getMemoryVT();
2912     // If we zero all the possible extended bits, then we can turn this into
2913     // a zextload if we are running before legalize or the operation is legal.
2914     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2915     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2916                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2917         ((!LegalOperations && !LN0->isVolatile()) ||
2918          TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2919       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2920                                        LN0->getChain(), LN0->getBasePtr(),
2921                                        MemVT, LN0->getMemOperand());
2922       AddToWorklist(N);
2923       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2924       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2925     }
2926   }
2927   // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
2928   if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
2929       N0.hasOneUse()) {
2930     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2931     EVT MemVT = LN0->getMemoryVT();
2932     // If we zero all the possible extended bits, then we can turn this into
2933     // a zextload if we are running before legalize or the operation is legal.
2934     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2935     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2936                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2937         ((!LegalOperations && !LN0->isVolatile()) ||
2938          TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2939       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2940                                        LN0->getChain(), LN0->getBasePtr(),
2941                                        MemVT, LN0->getMemOperand());
2942       AddToWorklist(N);
2943       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2944       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2945     }
2946   }
2947
2948   // fold (and (load x), 255) -> (zextload x, i8)
2949   // fold (and (extload x, i16), 255) -> (zextload x, i8)
2950   // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2951   if (N1C && (N0.getOpcode() == ISD::LOAD ||
2952               (N0.getOpcode() == ISD::ANY_EXTEND &&
2953                N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2954     bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2955     LoadSDNode *LN0 = HasAnyExt
2956       ? cast<LoadSDNode>(N0.getOperand(0))
2957       : cast<LoadSDNode>(N0);
2958     if (LN0->getExtensionType() != ISD::SEXTLOAD &&
2959         LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
2960       uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
2961       if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2962         EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2963         EVT LoadedVT = LN0->getMemoryVT();
2964
2965         if (ExtVT == LoadedVT &&
2966             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2967           EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2968
2969           SDValue NewLoad =
2970             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2971                            LN0->getChain(), LN0->getBasePtr(), ExtVT,
2972                            LN0->getMemOperand());
2973           AddToWorklist(N);
2974           CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2975           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2976         }
2977
2978         // Do not change the width of a volatile load.
2979         // Do not generate loads of non-round integer types since these can
2980         // be expensive (and would be wrong if the type is not byte sized).
2981         if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2982             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2983           EVT PtrType = LN0->getOperand(1).getValueType();
2984
2985           unsigned Alignment = LN0->getAlignment();
2986           SDValue NewPtr = LN0->getBasePtr();
2987
2988           // For big endian targets, we need to add an offset to the pointer
2989           // to load the correct bytes.  For little endian systems, we merely
2990           // need to read fewer bytes from the same pointer.
2991           if (TLI.isBigEndian()) {
2992             unsigned LVTStoreBytes = LoadedVT.getStoreSize();
2993             unsigned EVTStoreBytes = ExtVT.getStoreSize();
2994             unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
2995             NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
2996                                  NewPtr, DAG.getConstant(PtrOff, PtrType));
2997             Alignment = MinAlign(Alignment, PtrOff);
2998           }
2999
3000           AddToWorklist(NewPtr.getNode());
3001
3002           EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
3003           SDValue Load =
3004             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3005                            LN0->getChain(), NewPtr,
3006                            LN0->getPointerInfo(),
3007                            ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
3008                            LN0->isInvariant(), Alignment, LN0->getAAInfo());
3009           AddToWorklist(N);
3010           CombineTo(LN0, Load, Load.getValue(1));
3011           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3012         }
3013       }
3014     }
3015   }
3016
3017   if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
3018       VT.getSizeInBits() <= 64) {
3019     if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3020       APInt ADDC = ADDI->getAPIntValue();
3021       if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3022         // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
3023         // immediate for an add, but it is legal if its top c2 bits are set,
3024         // transform the ADD so the immediate doesn't need to be materialized
3025         // in a register.
3026         if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
3027           APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
3028                                              SRLI->getZExtValue());
3029           if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
3030             ADDC |= Mask;
3031             if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3032               SDValue NewAdd =
3033                 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
3034                             N0.getOperand(0), DAG.getConstant(ADDC, VT));
3035               CombineTo(N0.getNode(), NewAdd);
3036               return SDValue(N, 0); // Return N so it doesn't get rechecked!
3037             }
3038           }
3039         }
3040       }
3041     }
3042   }
3043
3044   // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3045   if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3046     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3047                                        N0.getOperand(1), false);
3048     if (BSwap.getNode())
3049       return BSwap;
3050   }
3051
3052   return SDValue();
3053 }
3054
3055 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
3056 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3057                                         bool DemandHighBits) {
3058   if (!LegalOperations)
3059     return SDValue();
3060
3061   EVT VT = N->getValueType(0);
3062   if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3063     return SDValue();
3064   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3065     return SDValue();
3066
3067   // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3068   bool LookPassAnd0 = false;
3069   bool LookPassAnd1 = false;
3070   if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3071       std::swap(N0, N1);
3072   if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3073       std::swap(N0, N1);
3074   if (N0.getOpcode() == ISD::AND) {
3075     if (!N0.getNode()->hasOneUse())
3076       return SDValue();
3077     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3078     if (!N01C || N01C->getZExtValue() != 0xFF00)
3079       return SDValue();
3080     N0 = N0.getOperand(0);
3081     LookPassAnd0 = true;
3082   }
3083
3084   if (N1.getOpcode() == ISD::AND) {
3085     if (!N1.getNode()->hasOneUse())
3086       return SDValue();
3087     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3088     if (!N11C || N11C->getZExtValue() != 0xFF)
3089       return SDValue();
3090     N1 = N1.getOperand(0);
3091     LookPassAnd1 = true;
3092   }
3093
3094   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3095     std::swap(N0, N1);
3096   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3097     return SDValue();
3098   if (!N0.getNode()->hasOneUse() ||
3099       !N1.getNode()->hasOneUse())
3100     return SDValue();
3101
3102   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3103   ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3104   if (!N01C || !N11C)
3105     return SDValue();
3106   if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3107     return SDValue();
3108
3109   // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3110   SDValue N00 = N0->getOperand(0);
3111   if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3112     if (!N00.getNode()->hasOneUse())
3113       return SDValue();
3114     ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3115     if (!N001C || N001C->getZExtValue() != 0xFF)
3116       return SDValue();
3117     N00 = N00.getOperand(0);
3118     LookPassAnd0 = true;
3119   }
3120
3121   SDValue N10 = N1->getOperand(0);
3122   if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3123     if (!N10.getNode()->hasOneUse())
3124       return SDValue();
3125     ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3126     if (!N101C || N101C->getZExtValue() != 0xFF00)
3127       return SDValue();
3128     N10 = N10.getOperand(0);
3129     LookPassAnd1 = true;
3130   }
3131
3132   if (N00 != N10)
3133     return SDValue();
3134
3135   // Make sure everything beyond the low halfword gets set to zero since the SRL
3136   // 16 will clear the top bits.
3137   unsigned OpSizeInBits = VT.getSizeInBits();
3138   if (DemandHighBits && OpSizeInBits > 16) {
3139     // If the left-shift isn't masked out then the only way this is a bswap is
3140     // if all bits beyond the low 8 are 0. In that case the entire pattern
3141     // reduces to a left shift anyway: leave it for other parts of the combiner.
3142     if (!LookPassAnd0)
3143       return SDValue();
3144
3145     // However, if the right shift isn't masked out then it might be because
3146     // it's not needed. See if we can spot that too.
3147     if (!LookPassAnd1 &&
3148         !DAG.MaskedValueIsZero(
3149             N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3150       return SDValue();
3151   }
3152
3153   SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3154   if (OpSizeInBits > 16)
3155     Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
3156                       DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
3157   return Res;
3158 }
3159
3160 /// Return true if the specified node is an element that makes up a 32-bit
3161 /// packed halfword byteswap.
3162 /// ((x & 0x000000ff) << 8) |
3163 /// ((x & 0x0000ff00) >> 8) |
3164 /// ((x & 0x00ff0000) << 8) |
3165 /// ((x & 0xff000000) >> 8)
3166 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
3167   if (!N.getNode()->hasOneUse())
3168     return false;
3169
3170   unsigned Opc = N.getOpcode();
3171   if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3172     return false;
3173
3174   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3175   if (!N1C)
3176     return false;
3177
3178   unsigned Num;
3179   switch (N1C->getZExtValue()) {
3180   default:
3181     return false;
3182   case 0xFF:       Num = 0; break;
3183   case 0xFF00:     Num = 1; break;
3184   case 0xFF0000:   Num = 2; break;
3185   case 0xFF000000: Num = 3; break;
3186   }
3187
3188   // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3189   SDValue N0 = N.getOperand(0);
3190   if (Opc == ISD::AND) {
3191     if (Num == 0 || Num == 2) {
3192       // (x >> 8) & 0xff
3193       // (x >> 8) & 0xff0000
3194       if (N0.getOpcode() != ISD::SRL)
3195         return false;
3196       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3197       if (!C || C->getZExtValue() != 8)
3198         return false;
3199     } else {
3200       // (x << 8) & 0xff00
3201       // (x << 8) & 0xff000000
3202       if (N0.getOpcode() != ISD::SHL)
3203         return false;
3204       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3205       if (!C || C->getZExtValue() != 8)
3206         return false;
3207     }
3208   } else if (Opc == ISD::SHL) {
3209     // (x & 0xff) << 8
3210     // (x & 0xff0000) << 8
3211     if (Num != 0 && Num != 2)
3212       return false;
3213     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3214     if (!C || C->getZExtValue() != 8)
3215       return false;
3216   } else { // Opc == ISD::SRL
3217     // (x & 0xff00) >> 8
3218     // (x & 0xff000000) >> 8
3219     if (Num != 1 && Num != 3)
3220       return false;
3221     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3222     if (!C || C->getZExtValue() != 8)
3223       return false;
3224   }
3225
3226   if (Parts[Num])
3227     return false;
3228
3229   Parts[Num] = N0.getOperand(0).getNode();
3230   return true;
3231 }
3232
3233 /// Match a 32-bit packed halfword bswap. That is
3234 /// ((x & 0x000000ff) << 8) |
3235 /// ((x & 0x0000ff00) >> 8) |
3236 /// ((x & 0x00ff0000) << 8) |
3237 /// ((x & 0xff000000) >> 8)
3238 /// => (rotl (bswap x), 16)
3239 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3240   if (!LegalOperations)
3241     return SDValue();
3242
3243   EVT VT = N->getValueType(0);
3244   if (VT != MVT::i32)
3245     return SDValue();
3246   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3247     return SDValue();
3248
3249   // Look for either
3250   // (or (or (and), (and)), (or (and), (and)))
3251   // (or (or (or (and), (and)), (and)), (and))
3252   if (N0.getOpcode() != ISD::OR)
3253     return SDValue();
3254   SDValue N00 = N0.getOperand(0);
3255   SDValue N01 = N0.getOperand(1);
3256   SDNode *Parts[4] = {};
3257
3258   if (N1.getOpcode() == ISD::OR &&
3259       N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3260     // (or (or (and), (and)), (or (and), (and)))
3261     SDValue N000 = N00.getOperand(0);
3262     if (!isBSwapHWordElement(N000, Parts))
3263       return SDValue();
3264
3265     SDValue N001 = N00.getOperand(1);
3266     if (!isBSwapHWordElement(N001, Parts))
3267       return SDValue();
3268     SDValue N010 = N01.getOperand(0);
3269     if (!isBSwapHWordElement(N010, Parts))
3270       return SDValue();
3271     SDValue N011 = N01.getOperand(1);
3272     if (!isBSwapHWordElement(N011, Parts))
3273       return SDValue();
3274   } else {
3275     // (or (or (or (and), (and)), (and)), (and))
3276     if (!isBSwapHWordElement(N1, Parts))
3277       return SDValue();
3278     if (!isBSwapHWordElement(N01, Parts))
3279       return SDValue();
3280     if (N00.getOpcode() != ISD::OR)
3281       return SDValue();
3282     SDValue N000 = N00.getOperand(0);
3283     if (!isBSwapHWordElement(N000, Parts))
3284       return SDValue();
3285     SDValue N001 = N00.getOperand(1);
3286     if (!isBSwapHWordElement(N001, Parts))
3287       return SDValue();
3288   }
3289
3290   // Make sure the parts are all coming from the same node.
3291   if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3292     return SDValue();
3293
3294   SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
3295                               SDValue(Parts[0],0));
3296
3297   // Result of the bswap should be rotated by 16. If it's not legal, then
3298   // do  (x << 16) | (x >> 16).
3299   SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3300   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3301     return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
3302   if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3303     return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3304   return DAG.getNode(ISD::OR, SDLoc(N), VT,
3305                      DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3306                      DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
3307 }
3308
3309 SDValue DAGCombiner::visitOR(SDNode *N) {
3310   SDValue N0 = N->getOperand(0);
3311   SDValue N1 = N->getOperand(1);
3312   SDValue LL, LR, RL, RR, CC0, CC1;
3313   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3314   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3315   EVT VT = N1.getValueType();
3316
3317   // fold vector ops
3318   if (VT.isVector()) {
3319     SDValue FoldedVOp = SimplifyVBinOp(N);
3320     if (FoldedVOp.getNode()) return FoldedVOp;
3321
3322     // fold (or x, 0) -> x, vector edition
3323     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3324       return N1;
3325     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3326       return N0;
3327
3328     // fold (or x, -1) -> -1, vector edition
3329     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3330       // do not return N0, because undef node may exist in N0
3331       return DAG.getConstant(
3332           APInt::getAllOnesValue(
3333               N0.getValueType().getScalarType().getSizeInBits()),
3334           N0.getValueType());
3335     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3336       // do not return N1, because undef node may exist in N1
3337       return DAG.getConstant(
3338           APInt::getAllOnesValue(
3339               N1.getValueType().getScalarType().getSizeInBits()),
3340           N1.getValueType());
3341
3342     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3343     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3344     // Do this only if the resulting shuffle is legal.
3345     if (isa<ShuffleVectorSDNode>(N0) &&
3346         isa<ShuffleVectorSDNode>(N1) &&
3347         // Avoid folding a node with illegal type.
3348         TLI.isTypeLegal(VT) &&
3349         N0->getOperand(1) == N1->getOperand(1) &&
3350         ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3351       bool CanFold = true;
3352       unsigned NumElts = VT.getVectorNumElements();
3353       const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3354       const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3355       // We construct two shuffle masks:
3356       // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3357       // and N1 as the second operand.
3358       // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3359       // and N0 as the second operand.
3360       // We do this because OR is commutable and therefore there might be
3361       // two ways to fold this node into a shuffle.
3362       SmallVector<int,4> Mask1;
3363       SmallVector<int,4> Mask2;
3364
3365       for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3366         int M0 = SV0->getMaskElt(i);
3367         int M1 = SV1->getMaskElt(i);
3368
3369         // Both shuffle indexes are undef. Propagate Undef.
3370         if (M0 < 0 && M1 < 0) {
3371           Mask1.push_back(M0);
3372           Mask2.push_back(M0);
3373           continue;
3374         }
3375
3376         if (M0 < 0 || M1 < 0 ||
3377             (M0 < (int)NumElts && M1 < (int)NumElts) ||
3378             (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3379           CanFold = false;
3380           break;
3381         }
3382
3383         Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3384         Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3385       }
3386
3387       if (CanFold) {
3388         // Fold this sequence only if the resulting shuffle is 'legal'.
3389         if (TLI.isShuffleMaskLegal(Mask1, VT))
3390           return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3391                                       N1->getOperand(0), &Mask1[0]);
3392         if (TLI.isShuffleMaskLegal(Mask2, VT))
3393           return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3394                                       N0->getOperand(0), &Mask2[0]);
3395       }
3396     }
3397   }
3398
3399   // fold (or x, undef) -> -1
3400   if (!LegalOperations &&
3401       (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3402     EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3403     return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3404   }
3405   // fold (or c1, c2) -> c1|c2
3406   if (N0C && N1C)
3407     return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
3408   // canonicalize constant to RHS
3409   if (N0C && !N1C)
3410     return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3411   // fold (or x, 0) -> x
3412   if (N1C && N1C->isNullValue())
3413     return N0;
3414   // fold (or x, -1) -> -1
3415   if (N1C && N1C->isAllOnesValue())
3416     return N1;
3417   // fold (or x, c) -> c iff (x & ~c) == 0
3418   if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3419     return N1;
3420
3421   // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3422   SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3423   if (BSwap.getNode())
3424     return BSwap;
3425   BSwap = MatchBSwapHWordLow(N, N0, N1);
3426   if (BSwap.getNode())
3427     return BSwap;
3428
3429   // reassociate or
3430   SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1);
3431   if (ROR.getNode())
3432     return ROR;
3433   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3434   // iff (c1 & c2) == 0.
3435   if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3436              isa<ConstantSDNode>(N0.getOperand(1))) {
3437     ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3438     if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3439       SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1);
3440       if (!COR.getNode())
3441         return SDValue();
3442       return DAG.getNode(ISD::AND, SDLoc(N), VT,
3443                          DAG.getNode(ISD::OR, SDLoc(N0), VT,
3444                                      N0.getOperand(0), N1), COR);
3445     }
3446   }
3447   // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3448   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3449     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3450     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3451
3452     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3453         LL.getValueType().isInteger()) {
3454       // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3455       // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3456       if (cast<ConstantSDNode>(LR)->isNullValue() &&
3457           (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3458         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3459                                      LR.getValueType(), LL, RL);
3460         AddToWorklist(ORNode.getNode());
3461         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
3462       }
3463       // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3464       // fold (or (setgt X, -1), (setgt Y  -1)) -> (setgt (and X, Y), -1)
3465       if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3466           (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3467         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3468                                       LR.getValueType(), LL, RL);
3469         AddToWorklist(ANDNode.getNode());
3470         return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
3471       }
3472     }
3473     // canonicalize equivalent to ll == rl
3474     if (LL == RR && LR == RL) {
3475       Op1 = ISD::getSetCCSwappedOperands(Op1);
3476       std::swap(RL, RR);
3477     }
3478     if (LL == RL && LR == RR) {
3479       bool isInteger = LL.getValueType().isInteger();
3480       ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3481       if (Result != ISD::SETCC_INVALID &&
3482           (!LegalOperations ||
3483            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3484             TLI.isOperationLegal(ISD::SETCC,
3485               getSetCCResultType(N0.getValueType())))))
3486         return DAG.getSetCC(SDLoc(N), N0.getValueType(),
3487                             LL, LR, Result);
3488     }
3489   }
3490
3491   // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
3492   if (N0.getOpcode() == N1.getOpcode()) {
3493     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3494     if (Tmp.getNode()) return Tmp;
3495   }
3496
3497   // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
3498   if (N0.getOpcode() == ISD::AND &&
3499       N1.getOpcode() == ISD::AND &&
3500       N0.getOperand(1).getOpcode() == ISD::Constant &&
3501       N1.getOperand(1).getOpcode() == ISD::Constant &&
3502       // Don't increase # computations.
3503       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3504     // We can only do this xform if we know that bits from X that are set in C2
3505     // but not in C1 are already zero.  Likewise for Y.
3506     const APInt &LHSMask =
3507       cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3508     const APInt &RHSMask =
3509       cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3510
3511     if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3512         DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3513       SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3514                               N0.getOperand(0), N1.getOperand(0));
3515       return DAG.getNode(ISD::AND, SDLoc(N), VT, X,
3516                          DAG.getConstant(LHSMask | RHSMask, VT));
3517     }
3518   }
3519
3520   // See if this is some rotate idiom.
3521   if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3522     return SDValue(Rot, 0);
3523
3524   // Simplify the operands using demanded-bits information.
3525   if (!VT.isVector() &&
3526       SimplifyDemandedBits(SDValue(N, 0)))
3527     return SDValue(N, 0);
3528
3529   return SDValue();
3530 }
3531
3532 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
3533 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3534   if (Op.getOpcode() == ISD::AND) {
3535     if (isa<ConstantSDNode>(Op.getOperand(1))) {
3536       Mask = Op.getOperand(1);
3537       Op = Op.getOperand(0);
3538     } else {
3539       return false;
3540     }
3541   }
3542
3543   if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3544     Shift = Op;
3545     return true;
3546   }
3547
3548   return false;
3549 }
3550
3551 // Return true if we can prove that, whenever Neg and Pos are both in the
3552 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos).  This means that
3553 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3554 //
3555 //     (or (shift1 X, Neg), (shift2 X, Pos))
3556 //
3557 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3558 // in direction shift1 by Neg.  The range [0, OpSize) means that we only need
3559 // to consider shift amounts with defined behavior.
3560 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3561   // If OpSize is a power of 2 then:
3562   //
3563   //  (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3564   //  (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3565   //
3566   // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3567   // for the stronger condition:
3568   //
3569   //     Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1)    [A]
3570   //
3571   // for all Neg and Pos.  Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3572   // we can just replace Neg with Neg' for the rest of the function.
3573   //
3574   // In other cases we check for the even stronger condition:
3575   //
3576   //     Neg == OpSize - Pos                                    [B]
3577   //
3578   // for all Neg and Pos.  Note that the (or ...) then invokes undefined
3579   // behavior if Pos == 0 (and consequently Neg == OpSize).
3580   //
3581   // We could actually use [A] whenever OpSize is a power of 2, but the
3582   // only extra cases that it would match are those uninteresting ones
3583   // where Neg and Pos are never in range at the same time.  E.g. for
3584   // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3585   // as well as (sub 32, Pos), but:
3586   //
3587   //     (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3588   //
3589   // always invokes undefined behavior for 32-bit X.
3590   //
3591   // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3592   unsigned MaskLoBits = 0;
3593   if (Neg.getOpcode() == ISD::AND &&
3594       isPowerOf2_64(OpSize) &&
3595       Neg.getOperand(1).getOpcode() == ISD::Constant &&
3596       cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3597     Neg = Neg.getOperand(0);
3598     MaskLoBits = Log2_64(OpSize);
3599   }
3600
3601   // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3602   if (Neg.getOpcode() != ISD::SUB)
3603     return 0;
3604   ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3605   if (!NegC)
3606     return 0;
3607   SDValue NegOp1 = Neg.getOperand(1);
3608
3609   // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3610   // Pos'.  The truncation is redundant for the purpose of the equality.
3611   if (MaskLoBits &&
3612       Pos.getOpcode() == ISD::AND &&
3613       Pos.getOperand(1).getOpcode() == ISD::Constant &&
3614       cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3615     Pos = Pos.getOperand(0);
3616
3617   // The condition we need is now:
3618   //
3619   //     (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3620   //
3621   // If NegOp1 == Pos then we need:
3622   //
3623   //              OpSize & Mask == NegC & Mask
3624   //
3625   // (because "x & Mask" is a truncation and distributes through subtraction).
3626   APInt Width;
3627   if (Pos == NegOp1)
3628     Width = NegC->getAPIntValue();
3629   // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3630   // Then the condition we want to prove becomes:
3631   //
3632   //     (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3633   //
3634   // which, again because "x & Mask" is a truncation, becomes:
3635   //
3636   //                NegC & Mask == (OpSize - PosC) & Mask
3637   //              OpSize & Mask == (NegC + PosC) & Mask
3638   else if (Pos.getOpcode() == ISD::ADD &&
3639            Pos.getOperand(0) == NegOp1 &&
3640            Pos.getOperand(1).getOpcode() == ISD::Constant)
3641     Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3642              NegC->getAPIntValue());
3643   else
3644     return false;
3645
3646   // Now we just need to check that OpSize & Mask == Width & Mask.
3647   if (MaskLoBits)
3648     // Opsize & Mask is 0 since Mask is Opsize - 1.
3649     return Width.getLoBits(MaskLoBits) == 0;
3650   return Width == OpSize;
3651 }
3652
3653 // A subroutine of MatchRotate used once we have found an OR of two opposite
3654 // shifts of Shifted.  If Neg == <operand size> - Pos then the OR reduces
3655 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3656 // former being preferred if supported.  InnerPos and InnerNeg are Pos and
3657 // Neg with outer conversions stripped away.
3658 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3659                                        SDValue Neg, SDValue InnerPos,
3660                                        SDValue InnerNeg, unsigned PosOpcode,
3661                                        unsigned NegOpcode, SDLoc DL) {
3662   // fold (or (shl x, (*ext y)),
3663   //          (srl x, (*ext (sub 32, y)))) ->
3664   //   (rotl x, y) or (rotr x, (sub 32, y))
3665   //
3666   // fold (or (shl x, (*ext (sub 32, y))),
3667   //          (srl x, (*ext y))) ->
3668   //   (rotr x, y) or (rotl x, (sub 32, y))
3669   EVT VT = Shifted.getValueType();
3670   if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3671     bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3672     return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3673                        HasPos ? Pos : Neg).getNode();
3674   }
3675
3676   return nullptr;
3677 }
3678
3679 // MatchRotate - Handle an 'or' of two operands.  If this is one of the many
3680 // idioms for rotate, and if the target supports rotation instructions, generate
3681 // a rot[lr].
3682 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3683   // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
3684   EVT VT = LHS.getValueType();
3685   if (!TLI.isTypeLegal(VT)) return nullptr;
3686
3687   // The target must have at least one rotate flavor.
3688   bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3689   bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3690   if (!HasROTL && !HasROTR) return nullptr;
3691
3692   // Match "(X shl/srl V1) & V2" where V2 may not be present.
3693   SDValue LHSShift;   // The shift.
3694   SDValue LHSMask;    // AND value if any.
3695   if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3696     return nullptr; // Not part of a rotate.
3697
3698   SDValue RHSShift;   // The shift.
3699   SDValue RHSMask;    // AND value if any.
3700   if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3701     return nullptr; // Not part of a rotate.
3702
3703   if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3704     return nullptr;   // Not shifting the same value.
3705
3706   if (LHSShift.getOpcode() == RHSShift.getOpcode())
3707     return nullptr;   // Shifts must disagree.
3708
3709   // Canonicalize shl to left side in a shl/srl pair.
3710   if (RHSShift.getOpcode() == ISD::SHL) {
3711     std::swap(LHS, RHS);
3712     std::swap(LHSShift, RHSShift);
3713     std::swap(LHSMask , RHSMask );
3714   }
3715
3716   unsigned OpSizeInBits = VT.getSizeInBits();
3717   SDValue LHSShiftArg = LHSShift.getOperand(0);
3718   SDValue LHSShiftAmt = LHSShift.getOperand(1);
3719   SDValue RHSShiftArg = RHSShift.getOperand(0);
3720   SDValue RHSShiftAmt = RHSShift.getOperand(1);
3721
3722   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3723   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3724   if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3725       RHSShiftAmt.getOpcode() == ISD::Constant) {
3726     uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3727     uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3728     if ((LShVal + RShVal) != OpSizeInBits)
3729       return nullptr;
3730
3731     SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3732                               LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3733
3734     // If there is an AND of either shifted operand, apply it to the result.
3735     if (LHSMask.getNode() || RHSMask.getNode()) {
3736       APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3737
3738       if (LHSMask.getNode()) {
3739         APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3740         Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3741       }
3742       if (RHSMask.getNode()) {
3743         APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3744         Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3745       }
3746
3747       Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
3748     }
3749
3750     return Rot.getNode();
3751   }
3752
3753   // If there is a mask here, and we have a variable shift, we can't be sure
3754   // that we're masking out the right stuff.
3755   if (LHSMask.getNode() || RHSMask.getNode())
3756     return nullptr;
3757
3758   // If the shift amount is sign/zext/any-extended just peel it off.
3759   SDValue LExtOp0 = LHSShiftAmt;
3760   SDValue RExtOp0 = RHSShiftAmt;
3761   if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3762        LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3763        LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3764        LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3765       (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3766        RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3767        RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3768        RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3769     LExtOp0 = LHSShiftAmt.getOperand(0);
3770     RExtOp0 = RHSShiftAmt.getOperand(0);
3771   }
3772
3773   SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3774                                    LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3775   if (TryL)
3776     return TryL;
3777
3778   SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3779                                    RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3780   if (TryR)
3781     return TryR;
3782
3783   return nullptr;
3784 }
3785
3786 SDValue DAGCombiner::visitXOR(SDNode *N) {
3787   SDValue N0 = N->getOperand(0);
3788   SDValue N1 = N->getOperand(1);
3789   SDValue LHS, RHS, CC;
3790   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3791   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3792   EVT VT = N0.getValueType();
3793
3794   // fold vector ops
3795   if (VT.isVector()) {
3796     SDValue FoldedVOp = SimplifyVBinOp(N);
3797     if (FoldedVOp.getNode()) return FoldedVOp;
3798
3799     // fold (xor x, 0) -> x, vector edition
3800     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3801       return N1;
3802     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3803       return N0;
3804   }
3805
3806   // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3807   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3808     return DAG.getConstant(0, VT);
3809   // fold (xor x, undef) -> undef
3810   if (N0.getOpcode() == ISD::UNDEF)
3811     return N0;
3812   if (N1.getOpcode() == ISD::UNDEF)
3813     return N1;
3814   // fold (xor c1, c2) -> c1^c2
3815   if (N0C && N1C)
3816     return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
3817   // canonicalize constant to RHS
3818   if (N0C && !N1C)
3819     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3820   // fold (xor x, 0) -> x
3821   if (N1C && N1C->isNullValue())
3822     return N0;
3823   // reassociate xor
3824   SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1);
3825   if (RXOR.getNode())
3826     return RXOR;
3827
3828   // fold !(x cc y) -> (x !cc y)
3829   if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3830     bool isInt = LHS.getValueType().isInteger();
3831     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3832                                                isInt);
3833
3834     if (!LegalOperations ||
3835         TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3836       switch (N0.getOpcode()) {
3837       default:
3838         llvm_unreachable("Unhandled SetCC Equivalent!");
3839       case ISD::SETCC:
3840         return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
3841       case ISD::SELECT_CC:
3842         return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
3843                                N0.getOperand(3), NotCC);
3844       }
3845     }
3846   }
3847
3848   // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3849   if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3850       N0.getNode()->hasOneUse() &&
3851       isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3852     SDValue V = N0.getOperand(0);
3853     V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
3854                     DAG.getConstant(1, V.getValueType()));
3855     AddToWorklist(V.getNode());
3856     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
3857   }
3858
3859   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3860   if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3861       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3862     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3863     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3864       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3865       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3866       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3867       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
3868       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3869     }
3870   }
3871   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
3872   if (N1C && N1C->isAllOnesValue() &&
3873       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3874     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3875     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3876       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3877       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3878       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3879       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
3880       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3881     }
3882   }
3883   // fold (xor (and x, y), y) -> (and (not x), y)
3884   if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3885       N0->getOperand(1) == N1) {
3886     SDValue X = N0->getOperand(0);
3887     SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
3888     AddToWorklist(NotX.getNode());
3889     return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
3890   }
3891   // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
3892   if (N1C && N0.getOpcode() == ISD::XOR) {
3893     ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3894     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3895     if (N00C)
3896       return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
3897                          DAG.getConstant(N1C->getAPIntValue() ^
3898                                          N00C->getAPIntValue(), VT));
3899     if (N01C)
3900       return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
3901                          DAG.getConstant(N1C->getAPIntValue() ^
3902                                          N01C->getAPIntValue(), VT));
3903   }
3904   // fold (xor x, x) -> 0
3905   if (N0 == N1)
3906     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
3907
3908   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
3909   if (N0.getOpcode() == N1.getOpcode()) {
3910     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3911     if (Tmp.getNode()) return Tmp;
3912   }
3913
3914   // Simplify the expression using non-local knowledge.
3915   if (!VT.isVector() &&
3916       SimplifyDemandedBits(SDValue(N, 0)))
3917     return SDValue(N, 0);
3918
3919   return SDValue();
3920 }
3921
3922 /// Handle transforms common to the three shifts, when the shift amount is a
3923 /// constant.
3924 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
3925   // We can't and shouldn't fold opaque constants.
3926   if (Amt->isOpaque())
3927     return SDValue();
3928
3929   SDNode *LHS = N->getOperand(0).getNode();
3930   if (!LHS->hasOneUse()) return SDValue();
3931
3932   // We want to pull some binops through shifts, so that we have (and (shift))
3933   // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
3934   // thing happens with address calculations, so it's important to canonicalize
3935   // it.
3936   bool HighBitSet = false;  // Can we transform this if the high bit is set?
3937
3938   switch (LHS->getOpcode()) {
3939   default: return SDValue();
3940   case ISD::OR:
3941   case ISD::XOR:
3942     HighBitSet = false; // We can only transform sra if the high bit is clear.
3943     break;
3944   case ISD::AND:
3945     HighBitSet = true;  // We can only transform sra if the high bit is set.
3946     break;
3947   case ISD::ADD:
3948     if (N->getOpcode() != ISD::SHL)
3949       return SDValue(); // only shl(add) not sr[al](add).
3950     HighBitSet = false; // We can only transform sra if the high bit is clear.
3951     break;
3952   }
3953
3954   // We require the RHS of the binop to be a constant and not opaque as well.
3955   ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
3956   if (!BinOpCst || BinOpCst->isOpaque()) return SDValue();
3957
3958   // FIXME: disable this unless the input to the binop is a shift by a constant.
3959   // If it is not a shift, it pessimizes some common cases like:
3960   //
3961   //    void foo(int *X, int i) { X[i & 1235] = 1; }
3962   //    int bar(int *X, int i) { return X[i & 255]; }
3963   SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
3964   if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
3965        BinOpLHSVal->getOpcode() != ISD::SRA &&
3966        BinOpLHSVal->getOpcode() != ISD::SRL) ||
3967       !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
3968     return SDValue();
3969
3970   EVT VT = N->getValueType(0);
3971
3972   // If this is a signed shift right, and the high bit is modified by the
3973   // logical operation, do not perform the transformation. The highBitSet
3974   // boolean indicates the value of the high bit of the constant which would
3975   // cause it to be modified for this operation.
3976   if (N->getOpcode() == ISD::SRA) {
3977     bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
3978     if (BinOpRHSSignSet != HighBitSet)
3979       return SDValue();
3980   }
3981
3982   if (!TLI.isDesirableToCommuteWithShift(LHS))
3983     return SDValue();
3984
3985   // Fold the constants, shifting the binop RHS by the shift amount.
3986   SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
3987                                N->getValueType(0),
3988                                LHS->getOperand(1), N->getOperand(1));
3989   assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
3990
3991   // Create the new shift.
3992   SDValue NewShift = DAG.getNode(N->getOpcode(),
3993                                  SDLoc(LHS->getOperand(0)),
3994                                  VT, LHS->getOperand(0), N->getOperand(1));
3995
3996   // Create the new binop.
3997   return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
3998 }
3999
4000 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
4001   assert(N->getOpcode() == ISD::TRUNCATE);
4002   assert(N->getOperand(0).getOpcode() == ISD::AND);
4003
4004   // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
4005   if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
4006     SDValue N01 = N->getOperand(0).getOperand(1);
4007
4008     if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
4009       EVT TruncVT = N->getValueType(0);
4010       SDValue N00 = N->getOperand(0).getOperand(0);
4011       APInt TruncC = N01C->getAPIntValue();
4012       TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
4013
4014       return DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
4015                          DAG.getNode(ISD::TRUNCATE, SDLoc(N), TruncVT, N00),
4016                          DAG.getConstant(TruncC, TruncVT));
4017     }
4018   }
4019
4020   return SDValue();
4021 }
4022
4023 SDValue DAGCombiner::visitRotate(SDNode *N) {
4024   // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
4025   if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
4026       N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
4027     SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
4028     if (NewOp1.getNode())
4029       return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
4030                          N->getOperand(0), NewOp1);
4031   }
4032   return SDValue();
4033 }
4034
4035 SDValue DAGCombiner::visitSHL(SDNode *N) {
4036   SDValue N0 = N->getOperand(0);
4037   SDValue N1 = N->getOperand(1);
4038   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4039   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4040   EVT VT = N0.getValueType();
4041   unsigned OpSizeInBits = VT.getScalarSizeInBits();
4042
4043   // fold vector ops
4044   if (VT.isVector()) {
4045     SDValue FoldedVOp = SimplifyVBinOp(N);
4046     if (FoldedVOp.getNode()) return FoldedVOp;
4047
4048     BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4049     // If setcc produces all-one true value then:
4050     // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
4051     if (N1CV && N1CV->isConstant()) {
4052       if (N0.getOpcode() == ISD::AND) {
4053         SDValue N00 = N0->getOperand(0);
4054         SDValue N01 = N0->getOperand(1);
4055         BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
4056
4057         if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4058             TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4059                 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4060           SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, VT, N01CV, N1CV);
4061           if (C.getNode())
4062             return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4063         }
4064       } else {
4065         N1C = isConstOrConstSplat(N1);
4066       }
4067     }
4068   }
4069
4070   // fold (shl c1, c2) -> c1<<c2
4071   if (N0C && N1C)
4072     return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
4073   // fold (shl 0, x) -> 0
4074   if (N0C && N0C->isNullValue())
4075     return N0;
4076   // fold (shl x, c >= size(x)) -> undef
4077   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4078     return DAG.getUNDEF(VT);
4079   // fold (shl x, 0) -> x
4080   if (N1C && N1C->isNullValue())
4081     return N0;
4082   // fold (shl undef, x) -> 0
4083   if (N0.getOpcode() == ISD::UNDEF)
4084     return DAG.getConstant(0, VT);
4085   // if (shl x, c) is known to be zero, return 0
4086   if (DAG.MaskedValueIsZero(SDValue(N, 0),
4087                             APInt::getAllOnesValue(OpSizeInBits)))
4088     return DAG.getConstant(0, VT);
4089   // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4090   if (N1.getOpcode() == ISD::TRUNCATE &&
4091       N1.getOperand(0).getOpcode() == ISD::AND) {
4092     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4093     if (NewOp1.getNode())
4094       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4095   }
4096
4097   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4098     return SDValue(N, 0);
4099
4100   // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4101   if (N1C && N0.getOpcode() == ISD::SHL) {
4102     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4103       uint64_t c1 = N0C1->getZExtValue();
4104       uint64_t c2 = N1C->getZExtValue();
4105       if (c1 + c2 >= OpSizeInBits)
4106         return DAG.getConstant(0, VT);
4107       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4108                          DAG.getConstant(c1 + c2, N1.getValueType()));
4109     }
4110   }
4111
4112   // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4113   // For this to be valid, the second form must not preserve any of the bits
4114   // that are shifted out by the inner shift in the first form.  This means
4115   // the outer shift size must be >= the number of bits added by the ext.
4116   // As a corollary, we don't care what kind of ext it is.
4117   if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4118               N0.getOpcode() == ISD::ANY_EXTEND ||
4119               N0.getOpcode() == ISD::SIGN_EXTEND) &&
4120       N0.getOperand(0).getOpcode() == ISD::SHL) {
4121     SDValue N0Op0 = N0.getOperand(0);
4122     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4123       uint64_t c1 = N0Op0C1->getZExtValue();
4124       uint64_t c2 = N1C->getZExtValue();
4125       EVT InnerShiftVT = N0Op0.getValueType();
4126       uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4127       if (c2 >= OpSizeInBits - InnerShiftSize) {
4128         if (c1 + c2 >= OpSizeInBits)
4129           return DAG.getConstant(0, VT);
4130         return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
4131                            DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
4132                                        N0Op0->getOperand(0)),
4133                            DAG.getConstant(c1 + c2, N1.getValueType()));
4134       }
4135     }
4136   }
4137
4138   // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4139   // Only fold this if the inner zext has no other uses to avoid increasing
4140   // the total number of instructions.
4141   if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4142       N0.getOperand(0).getOpcode() == ISD::SRL) {
4143     SDValue N0Op0 = N0.getOperand(0);
4144     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4145       uint64_t c1 = N0Op0C1->getZExtValue();
4146       if (c1 < VT.getScalarSizeInBits()) {
4147         uint64_t c2 = N1C->getZExtValue();
4148         if (c1 == c2) {
4149           SDValue NewOp0 = N0.getOperand(0);
4150           EVT CountVT = NewOp0.getOperand(1).getValueType();
4151           SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(),
4152                                        NewOp0, DAG.getConstant(c2, CountVT));
4153           AddToWorklist(NewSHL.getNode());
4154           return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4155         }
4156       }
4157     }
4158   }
4159
4160   // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4161   //                               (and (srl x, (sub c1, c2), MASK)
4162   // Only fold this if the inner shift has no other uses -- if it does, folding
4163   // this will increase the total number of instructions.
4164   if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4165     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4166       uint64_t c1 = N0C1->getZExtValue();
4167       if (c1 < OpSizeInBits) {
4168         uint64_t c2 = N1C->getZExtValue();
4169         APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4170         SDValue Shift;
4171         if (c2 > c1) {
4172           Mask = Mask.shl(c2 - c1);
4173           Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4174                               DAG.getConstant(c2 - c1, N1.getValueType()));
4175         } else {
4176           Mask = Mask.lshr(c1 - c2);
4177           Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4178                               DAG.getConstant(c1 - c2, N1.getValueType()));
4179         }
4180         return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
4181                            DAG.getConstant(Mask, VT));
4182       }
4183     }
4184   }
4185   // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4186   if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4187     unsigned BitSize = VT.getScalarSizeInBits();
4188     SDValue HiBitsMask =
4189       DAG.getConstant(APInt::getHighBitsSet(BitSize,
4190                                             BitSize - N1C->getZExtValue()), VT);
4191     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4192                        HiBitsMask);
4193   }
4194
4195   // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
4196   // Variant of version done on multiply, except mul by a power of 2 is turned
4197   // into a shift.
4198   APInt Val;
4199   if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
4200       (isa<ConstantSDNode>(N0.getOperand(1)) ||
4201        isConstantSplatVector(N0.getOperand(1).getNode(), Val))) {
4202     SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
4203     SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
4204     return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
4205   }
4206
4207   if (N1C) {
4208     SDValue NewSHL = visitShiftByConstant(N, N1C);
4209     if (NewSHL.getNode())
4210       return NewSHL;
4211   }
4212
4213   return SDValue();
4214 }
4215
4216 SDValue DAGCombiner::visitSRA(SDNode *N) {
4217   SDValue N0 = N->getOperand(0);
4218   SDValue N1 = N->getOperand(1);
4219   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4220   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4221   EVT VT = N0.getValueType();
4222   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4223
4224   // fold vector ops
4225   if (VT.isVector()) {
4226     SDValue FoldedVOp = SimplifyVBinOp(N);
4227     if (FoldedVOp.getNode()) return FoldedVOp;
4228
4229     N1C = isConstOrConstSplat(N1);
4230   }
4231
4232   // fold (sra c1, c2) -> (sra c1, c2)
4233   if (N0C && N1C)
4234     return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
4235   // fold (sra 0, x) -> 0
4236   if (N0C && N0C->isNullValue())
4237     return N0;
4238   // fold (sra -1, x) -> -1
4239   if (N0C && N0C->isAllOnesValue())
4240     return N0;
4241   // fold (sra x, (setge c, size(x))) -> undef
4242   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4243     return DAG.getUNDEF(VT);
4244   // fold (sra x, 0) -> x
4245   if (N1C && N1C->isNullValue())
4246     return N0;
4247   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4248   // sext_inreg.
4249   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4250     unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4251     EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4252     if (VT.isVector())
4253       ExtVT = EVT::getVectorVT(*DAG.getContext(),
4254                                ExtVT, VT.getVectorNumElements());
4255     if ((!LegalOperations ||
4256          TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4257       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4258                          N0.getOperand(0), DAG.getValueType(ExtVT));
4259   }
4260
4261   // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4262   if (N1C && N0.getOpcode() == ISD::SRA) {
4263     if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4264       unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4265       if (Sum >= OpSizeInBits)
4266         Sum = OpSizeInBits - 1;
4267       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
4268                          DAG.getConstant(Sum, N1.getValueType()));
4269     }
4270   }
4271
4272   // fold (sra (shl X, m), (sub result_size, n))
4273   // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4274   // result_size - n != m.
4275   // If truncate is free for the target sext(shl) is likely to result in better
4276   // code.
4277   if (N0.getOpcode() == ISD::SHL && N1C) {
4278     // Get the two constanst of the shifts, CN0 = m, CN = n.
4279     const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4280     if (N01C) {
4281       LLVMContext &Ctx = *DAG.getContext();
4282       // Determine what the truncate's result bitsize and type would be.
4283       EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4284
4285       if (VT.isVector())
4286         TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4287
4288       // Determine the residual right-shift amount.
4289       signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4290
4291       // If the shift is not a no-op (in which case this should be just a sign
4292       // extend already), the truncated to type is legal, sign_extend is legal
4293       // on that type, and the truncate to that type is both legal and free,
4294       // perform the transform.
4295       if ((ShiftAmt > 0) &&
4296           TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4297           TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4298           TLI.isTruncateFree(VT, TruncVT)) {
4299
4300           SDValue Amt = DAG.getConstant(ShiftAmt,
4301               getShiftAmountTy(N0.getOperand(0).getValueType()));
4302           SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
4303                                       N0.getOperand(0), Amt);
4304           SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
4305                                       Shift);
4306           return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
4307                              N->getValueType(0), Trunc);
4308       }
4309     }
4310   }
4311
4312   // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4313   if (N1.getOpcode() == ISD::TRUNCATE &&
4314       N1.getOperand(0).getOpcode() == ISD::AND) {
4315     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4316     if (NewOp1.getNode())
4317       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4318   }
4319
4320   // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4321   //      if c1 is equal to the number of bits the trunc removes
4322   if (N0.getOpcode() == ISD::TRUNCATE &&
4323       (N0.getOperand(0).getOpcode() == ISD::SRL ||
4324        N0.getOperand(0).getOpcode() == ISD::SRA) &&
4325       N0.getOperand(0).hasOneUse() &&
4326       N0.getOperand(0).getOperand(1).hasOneUse() &&
4327       N1C) {
4328     SDValue N0Op0 = N0.getOperand(0);
4329     if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4330       unsigned LargeShiftVal = LargeShift->getZExtValue();
4331       EVT LargeVT = N0Op0.getValueType();
4332
4333       if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4334         SDValue Amt =
4335           DAG.getConstant(LargeShiftVal + N1C->getZExtValue(),
4336                           getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4337         SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
4338                                   N0Op0.getOperand(0), Amt);
4339         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
4340       }
4341     }
4342   }
4343
4344   // Simplify, based on bits shifted out of the LHS.
4345   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4346     return SDValue(N, 0);
4347
4348
4349   // If the sign bit is known to be zero, switch this to a SRL.
4350   if (DAG.SignBitIsZero(N0))
4351     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4352
4353   if (N1C) {
4354     SDValue NewSRA = visitShiftByConstant(N, N1C);
4355     if (NewSRA.getNode())
4356       return NewSRA;
4357   }
4358
4359   return SDValue();
4360 }
4361
4362 SDValue DAGCombiner::visitSRL(SDNode *N) {
4363   SDValue N0 = N->getOperand(0);
4364   SDValue N1 = N->getOperand(1);
4365   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4366   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4367   EVT VT = N0.getValueType();
4368   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4369
4370   // fold vector ops
4371   if (VT.isVector()) {
4372     SDValue FoldedVOp = SimplifyVBinOp(N);
4373     if (FoldedVOp.getNode()) return FoldedVOp;
4374
4375     N1C = isConstOrConstSplat(N1);
4376   }
4377
4378   // fold (srl c1, c2) -> c1 >>u c2
4379   if (N0C && N1C)
4380     return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
4381   // fold (srl 0, x) -> 0
4382   if (N0C && N0C->isNullValue())
4383     return N0;
4384   // fold (srl x, c >= size(x)) -> undef
4385   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4386     return DAG.getUNDEF(VT);
4387   // fold (srl x, 0) -> x
4388   if (N1C && N1C->isNullValue())
4389     return N0;
4390   // if (srl x, c) is known to be zero, return 0
4391   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4392                                    APInt::getAllOnesValue(OpSizeInBits)))
4393     return DAG.getConstant(0, VT);
4394
4395   // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4396   if (N1C && N0.getOpcode() == ISD::SRL) {
4397     if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4398       uint64_t c1 = N01C->getZExtValue();
4399       uint64_t c2 = N1C->getZExtValue();
4400       if (c1 + c2 >= OpSizeInBits)
4401         return DAG.getConstant(0, VT);
4402       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4403                          DAG.getConstant(c1 + c2, N1.getValueType()));
4404     }
4405   }
4406
4407   // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4408   if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4409       N0.getOperand(0).getOpcode() == ISD::SRL &&
4410       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4411     uint64_t c1 =
4412       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4413     uint64_t c2 = N1C->getZExtValue();
4414     EVT InnerShiftVT = N0.getOperand(0).getValueType();
4415     EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4416     uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4417     // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4418     if (c1 + OpSizeInBits == InnerShiftSize) {
4419       if (c1 + c2 >= InnerShiftSize)
4420         return DAG.getConstant(0, VT);
4421       return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
4422                          DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
4423                                      N0.getOperand(0)->getOperand(0),
4424                                      DAG.getConstant(c1 + c2, ShiftCountVT)));
4425     }
4426   }
4427
4428   // fold (srl (shl x, c), c) -> (and x, cst2)
4429   if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4430     unsigned BitSize = N0.getScalarValueSizeInBits();
4431     if (BitSize <= 64) {
4432       uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4433       return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4434                          DAG.getConstant(~0ULL >> ShAmt, VT));
4435     }
4436   }
4437
4438   // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4439   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4440     // Shifting in all undef bits?
4441     EVT SmallVT = N0.getOperand(0).getValueType();
4442     unsigned BitSize = SmallVT.getScalarSizeInBits();
4443     if (N1C->getZExtValue() >= BitSize)
4444       return DAG.getUNDEF(VT);
4445
4446     if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4447       uint64_t ShiftAmt = N1C->getZExtValue();
4448       SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
4449                                        N0.getOperand(0),
4450                           DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
4451       AddToWorklist(SmallShift.getNode());
4452       APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4453       return DAG.getNode(ISD::AND, SDLoc(N), VT,
4454                          DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
4455                          DAG.getConstant(Mask, VT));
4456     }
4457   }
4458
4459   // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
4460   // bit, which is unmodified by sra.
4461   if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4462     if (N0.getOpcode() == ISD::SRA)
4463       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4464   }
4465
4466   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
4467   if (N1C && N0.getOpcode() == ISD::CTLZ &&
4468       N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4469     APInt KnownZero, KnownOne;
4470     DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
4471
4472     // If any of the input bits are KnownOne, then the input couldn't be all
4473     // zeros, thus the result of the srl will always be zero.
4474     if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
4475
4476     // If all of the bits input the to ctlz node are known to be zero, then
4477     // the result of the ctlz is "32" and the result of the shift is one.
4478     APInt UnknownBits = ~KnownZero;
4479     if (UnknownBits == 0) return DAG.getConstant(1, VT);
4480
4481     // Otherwise, check to see if there is exactly one bit input to the ctlz.
4482     if ((UnknownBits & (UnknownBits - 1)) == 0) {
4483       // Okay, we know that only that the single bit specified by UnknownBits
4484       // could be set on input to the CTLZ node. If this bit is set, the SRL
4485       // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4486       // to an SRL/XOR pair, which is likely to simplify more.
4487       unsigned ShAmt = UnknownBits.countTrailingZeros();
4488       SDValue Op = N0.getOperand(0);
4489
4490       if (ShAmt) {
4491         Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
4492                   DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
4493         AddToWorklist(Op.getNode());
4494       }
4495
4496       return DAG.getNode(ISD::XOR, SDLoc(N), VT,
4497                          Op, DAG.getConstant(1, VT));
4498     }
4499   }
4500
4501   // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4502   if (N1.getOpcode() == ISD::TRUNCATE &&
4503       N1.getOperand(0).getOpcode() == ISD::AND) {
4504     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4505     if (NewOp1.getNode())
4506       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4507   }
4508
4509   // fold operands of srl based on knowledge that the low bits are not
4510   // demanded.
4511   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4512     return SDValue(N, 0);
4513
4514   if (N1C) {
4515     SDValue NewSRL = visitShiftByConstant(N, N1C);
4516     if (NewSRL.getNode())
4517       return NewSRL;
4518   }
4519
4520   // Attempt to convert a srl of a load into a narrower zero-extending load.
4521   SDValue NarrowLoad = ReduceLoadWidth(N);
4522   if (NarrowLoad.getNode())
4523     return NarrowLoad;
4524
4525   // Here is a common situation. We want to optimize:
4526   //
4527   //   %a = ...
4528   //   %b = and i32 %a, 2
4529   //   %c = srl i32 %b, 1
4530   //   brcond i32 %c ...
4531   //
4532   // into
4533   //
4534   //   %a = ...
4535   //   %b = and %a, 2
4536   //   %c = setcc eq %b, 0
4537   //   brcond %c ...
4538   //
4539   // However when after the source operand of SRL is optimized into AND, the SRL
4540   // itself may not be optimized further. Look for it and add the BRCOND into
4541   // the worklist.
4542   if (N->hasOneUse()) {
4543     SDNode *Use = *N->use_begin();
4544     if (Use->getOpcode() == ISD::BRCOND)
4545       AddToWorklist(Use);
4546     else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4547       // Also look pass the truncate.
4548       Use = *Use->use_begin();
4549       if (Use->getOpcode() == ISD::BRCOND)
4550         AddToWorklist(Use);
4551     }
4552   }
4553
4554   return SDValue();
4555 }
4556
4557 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4558   SDValue N0 = N->getOperand(0);
4559   EVT VT = N->getValueType(0);
4560
4561   // fold (ctlz c1) -> c2
4562   if (isa<ConstantSDNode>(N0))
4563     return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4564   return SDValue();
4565 }
4566
4567 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4568   SDValue N0 = N->getOperand(0);
4569   EVT VT = N->getValueType(0);
4570
4571   // fold (ctlz_zero_undef c1) -> c2
4572   if (isa<ConstantSDNode>(N0))
4573     return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4574   return SDValue();
4575 }
4576
4577 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4578   SDValue N0 = N->getOperand(0);
4579   EVT VT = N->getValueType(0);
4580
4581   // fold (cttz c1) -> c2
4582   if (isa<ConstantSDNode>(N0))
4583     return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4584   return SDValue();
4585 }
4586
4587 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4588   SDValue N0 = N->getOperand(0);
4589   EVT VT = N->getValueType(0);
4590
4591   // fold (cttz_zero_undef c1) -> c2
4592   if (isa<ConstantSDNode>(N0))
4593     return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4594   return SDValue();
4595 }
4596
4597 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4598   SDValue N0 = N->getOperand(0);
4599   EVT VT = N->getValueType(0);
4600
4601   // fold (ctpop c1) -> c2
4602   if (isa<ConstantSDNode>(N0))
4603     return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4604   return SDValue();
4605 }
4606
4607 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4608   SDValue N0 = N->getOperand(0);
4609   SDValue N1 = N->getOperand(1);
4610   SDValue N2 = N->getOperand(2);
4611   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4612   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4613   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4614   EVT VT = N->getValueType(0);
4615   EVT VT0 = N0.getValueType();
4616
4617   // fold (select C, X, X) -> X
4618   if (N1 == N2)
4619     return N1;
4620   // fold (select true, X, Y) -> X
4621   if (N0C && !N0C->isNullValue())
4622     return N1;
4623   // fold (select false, X, Y) -> Y
4624   if (N0C && N0C->isNullValue())
4625     return N2;
4626   // fold (select C, 1, X) -> (or C, X)
4627   if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
4628     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4629   // fold (select C, 0, 1) -> (xor C, 1)
4630   // We can't do this reliably if integer based booleans have different contents
4631   // to floating point based booleans. This is because we can't tell whether we
4632   // have an integer-based boolean or a floating-point-based boolean unless we
4633   // can find the SETCC that produced it and inspect its operands. This is
4634   // fairly easy if C is the SETCC node, but it can potentially be
4635   // undiscoverable (or not reasonably discoverable). For example, it could be
4636   // in another basic block or it could require searching a complicated
4637   // expression.
4638   if (VT.isInteger() &&
4639       (VT0 == MVT::i1 || (VT0.isInteger() &&
4640                           TLI.getBooleanContents(false, false) ==
4641                               TLI.getBooleanContents(false, true) &&
4642                           TLI.getBooleanContents(false, false) ==
4643                               TargetLowering::ZeroOrOneBooleanContent)) &&
4644       N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
4645     SDValue XORNode;
4646     if (VT == VT0)
4647       return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
4648                          N0, DAG.getConstant(1, VT0));
4649     XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
4650                           N0, DAG.getConstant(1, VT0));
4651     AddToWorklist(XORNode.getNode());
4652     if (VT.bitsGT(VT0))
4653       return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4654     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4655   }
4656   // fold (select C, 0, X) -> (and (not C), X)
4657   if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
4658     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4659     AddToWorklist(NOTNode.getNode());
4660     return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4661   }
4662   // fold (select C, X, 1) -> (or (not C), X)
4663   if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4664     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4665     AddToWorklist(NOTNode.getNode());
4666     return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4667   }
4668   // fold (select C, X, 0) -> (and C, X)
4669   if (VT == MVT::i1 && N2C && N2C->isNullValue())
4670     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4671   // fold (select X, X, Y) -> (or X, Y)
4672   // fold (select X, 1, Y) -> (or X, Y)
4673   if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4674     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4675   // fold (select X, Y, X) -> (and X, Y)
4676   // fold (select X, Y, 0) -> (and X, Y)
4677   if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
4678     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4679
4680   // If we can fold this based on the true/false value, do so.
4681   if (SimplifySelectOps(N, N1, N2))
4682     return SDValue(N, 0);  // Don't revisit N.
4683
4684   // fold selects based on a setcc into other things, such as min/max/abs
4685   if (N0.getOpcode() == ISD::SETCC) {
4686     if ((!LegalOperations &&
4687          TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
4688         TLI.isOperationLegal(ISD::SELECT_CC, VT))
4689       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4690                          N0.getOperand(0), N0.getOperand(1),
4691                          N1, N2, N0.getOperand(2));
4692     return SimplifySelect(SDLoc(N), N0, N1, N2);
4693   }
4694
4695   return SDValue();
4696 }
4697
4698 static
4699 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
4700   SDLoc DL(N);
4701   EVT LoVT, HiVT;
4702   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
4703
4704   // Split the inputs.
4705   SDValue Lo, Hi, LL, LH, RL, RH;
4706   std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
4707   std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
4708
4709   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
4710   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
4711
4712   return std::make_pair(Lo, Hi);
4713 }
4714
4715 // This function assumes all the vselect's arguments are CONCAT_VECTOR
4716 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
4717 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
4718   SDLoc dl(N);
4719   SDValue Cond = N->getOperand(0);
4720   SDValue LHS = N->getOperand(1);
4721   SDValue RHS = N->getOperand(2);
4722   EVT VT = N->getValueType(0);
4723   int NumElems = VT.getVectorNumElements();
4724   assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
4725          RHS.getOpcode() == ISD::CONCAT_VECTORS &&
4726          Cond.getOpcode() == ISD::BUILD_VECTOR);
4727
4728   // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
4729   // binary ones here.
4730   if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
4731     return SDValue();
4732
4733   // We're sure we have an even number of elements due to the
4734   // concat_vectors we have as arguments to vselect.
4735   // Skip BV elements until we find one that's not an UNDEF
4736   // After we find an UNDEF element, keep looping until we get to half the
4737   // length of the BV and see if all the non-undef nodes are the same.
4738   ConstantSDNode *BottomHalf = nullptr;
4739   for (int i = 0; i < NumElems / 2; ++i) {
4740     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4741       continue;
4742
4743     if (BottomHalf == nullptr)
4744       BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4745     else if (Cond->getOperand(i).getNode() != BottomHalf)
4746       return SDValue();
4747   }
4748
4749   // Do the same for the second half of the BuildVector
4750   ConstantSDNode *TopHalf = nullptr;
4751   for (int i = NumElems / 2; i < NumElems; ++i) {
4752     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4753       continue;
4754
4755     if (TopHalf == nullptr)
4756       TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4757     else if (Cond->getOperand(i).getNode() != TopHalf)
4758       return SDValue();
4759   }
4760
4761   assert(TopHalf && BottomHalf &&
4762          "One half of the selector was all UNDEFs and the other was all the "
4763          "same value. This should have been addressed before this function.");
4764   return DAG.getNode(
4765       ISD::CONCAT_VECTORS, dl, VT,
4766       BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
4767       TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
4768 }
4769
4770 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
4771   SDValue N0 = N->getOperand(0);
4772   SDValue N1 = N->getOperand(1);
4773   SDValue N2 = N->getOperand(2);
4774   SDLoc DL(N);
4775
4776   // Canonicalize integer abs.
4777   // vselect (setg[te] X,  0),  X, -X ->
4778   // vselect (setgt    X, -1),  X, -X ->
4779   // vselect (setl[te] X,  0), -X,  X ->
4780   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
4781   if (N0.getOpcode() == ISD::SETCC) {
4782     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4783     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4784     bool isAbs = false;
4785     bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
4786
4787     if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
4788          (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
4789         N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
4790       isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
4791     else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
4792              N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
4793       isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4794
4795     if (isAbs) {
4796       EVT VT = LHS.getValueType();
4797       SDValue Shift = DAG.getNode(
4798           ISD::SRA, DL, VT, LHS,
4799           DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
4800       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
4801       AddToWorklist(Shift.getNode());
4802       AddToWorklist(Add.getNode());
4803       return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
4804     }
4805   }
4806
4807   // If the VSELECT result requires splitting and the mask is provided by a
4808   // SETCC, then split both nodes and its operands before legalization. This
4809   // prevents the type legalizer from unrolling SETCC into scalar comparisons
4810   // and enables future optimizations (e.g. min/max pattern matching on X86).
4811   if (N0.getOpcode() == ISD::SETCC) {
4812     EVT VT = N->getValueType(0);
4813
4814     // Check if any splitting is required.
4815     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
4816         TargetLowering::TypeSplitVector)
4817       return SDValue();
4818
4819     SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
4820     std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
4821     std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
4822     std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
4823
4824     Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
4825     Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
4826
4827     // Add the new VSELECT nodes to the work list in case they need to be split
4828     // again.
4829     AddToWorklist(Lo.getNode());
4830     AddToWorklist(Hi.getNode());
4831
4832     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
4833   }
4834
4835   // Fold (vselect (build_vector all_ones), N1, N2) -> N1
4836   if (ISD::isBuildVectorAllOnes(N0.getNode()))
4837     return N1;
4838   // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
4839   if (ISD::isBuildVectorAllZeros(N0.getNode()))
4840     return N2;
4841
4842   // The ConvertSelectToConcatVector function is assuming both the above
4843   // checks for (vselect (build_vector all{ones,zeros) ...) have been made
4844   // and addressed.
4845   if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
4846       N2.getOpcode() == ISD::CONCAT_VECTORS &&
4847       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
4848     SDValue CV = ConvertSelectToConcatVector(N, DAG);
4849     if (CV.getNode())
4850       return CV;
4851   }
4852
4853   return SDValue();
4854 }
4855
4856 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
4857   SDValue N0 = N->getOperand(0);
4858   SDValue N1 = N->getOperand(1);
4859   SDValue N2 = N->getOperand(2);
4860   SDValue N3 = N->getOperand(3);
4861   SDValue N4 = N->getOperand(4);
4862   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
4863
4864   // fold select_cc lhs, rhs, x, x, cc -> x
4865   if (N2 == N3)
4866     return N2;
4867
4868   // Determine if the condition we're dealing with is constant
4869   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
4870                               N0, N1, CC, SDLoc(N), false);
4871   if (SCC.getNode()) {
4872     AddToWorklist(SCC.getNode());
4873
4874     if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
4875       if (!SCCC->isNullValue())
4876         return N2;    // cond always true -> true val
4877       else
4878         return N3;    // cond always false -> false val
4879     }
4880
4881     // Fold to a simpler select_cc
4882     if (SCC.getOpcode() == ISD::SETCC)
4883       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
4884                          SCC.getOperand(0), SCC.getOperand(1), N2, N3,
4885                          SCC.getOperand(2));
4886   }
4887
4888   // If we can fold this based on the true/false value, do so.
4889   if (SimplifySelectOps(N, N2, N3))
4890     return SDValue(N, 0);  // Don't revisit N.
4891
4892   // fold select_cc into other things, such as min/max/abs
4893   return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
4894 }
4895
4896 SDValue DAGCombiner::visitSETCC(SDNode *N) {
4897   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
4898                        cast<CondCodeSDNode>(N->getOperand(2))->get(),
4899                        SDLoc(N));
4900 }
4901
4902 // tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
4903 // dag node into a ConstantSDNode or a build_vector of constants.
4904 // This function is called by the DAGCombiner when visiting sext/zext/aext
4905 // dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
4906 // Vector extends are not folded if operations are legal; this is to
4907 // avoid introducing illegal build_vector dag nodes.
4908 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
4909                                          SelectionDAG &DAG, bool LegalTypes,
4910                                          bool LegalOperations) {
4911   unsigned Opcode = N->getOpcode();
4912   SDValue N0 = N->getOperand(0);
4913   EVT VT = N->getValueType(0);
4914
4915   assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
4916          Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
4917
4918   // fold (sext c1) -> c1
4919   // fold (zext c1) -> c1
4920   // fold (aext c1) -> c1
4921   if (isa<ConstantSDNode>(N0))
4922     return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
4923
4924   // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
4925   // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
4926   // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
4927   EVT SVT = VT.getScalarType();
4928   if (!(VT.isVector() &&
4929       (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
4930       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
4931     return nullptr;
4932
4933   // We can fold this node into a build_vector.
4934   unsigned VTBits = SVT.getSizeInBits();
4935   unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
4936   unsigned ShAmt = VTBits - EVTBits;
4937   SmallVector<SDValue, 8> Elts;
4938   unsigned NumElts = N0->getNumOperands();
4939   SDLoc DL(N);
4940
4941   for (unsigned i=0; i != NumElts; ++i) {
4942     SDValue Op = N0->getOperand(i);
4943     if (Op->getOpcode() == ISD::UNDEF) {
4944       Elts.push_back(DAG.getUNDEF(SVT));
4945       continue;
4946     }
4947
4948     ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
4949     const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
4950     if (Opcode == ISD::SIGN_EXTEND)
4951       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
4952                                      SVT));
4953     else
4954       Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
4955                                      SVT));
4956   }
4957
4958   return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
4959 }
4960
4961 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
4962 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
4963 // transformation. Returns true if extension are possible and the above
4964 // mentioned transformation is profitable.
4965 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
4966                                     unsigned ExtOpc,
4967                                     SmallVectorImpl<SDNode *> &ExtendNodes,
4968                                     const TargetLowering &TLI) {
4969   bool HasCopyToRegUses = false;
4970   bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
4971   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
4972                             UE = N0.getNode()->use_end();
4973        UI != UE; ++UI) {
4974     SDNode *User = *UI;
4975     if (User == N)
4976       continue;
4977     if (UI.getUse().getResNo() != N0.getResNo())
4978       continue;
4979     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
4980     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
4981       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
4982       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
4983         // Sign bits will be lost after a zext.
4984         return false;
4985       bool Add = false;
4986       for (unsigned i = 0; i != 2; ++i) {
4987         SDValue UseOp = User->getOperand(i);
4988         if (UseOp == N0)
4989           continue;
4990         if (!isa<ConstantSDNode>(UseOp))
4991           return false;
4992         Add = true;
4993       }
4994       if (Add)
4995         ExtendNodes.push_back(User);
4996       continue;
4997     }
4998     // If truncates aren't free and there are users we can't
4999     // extend, it isn't worthwhile.
5000     if (!isTruncFree)
5001       return false;
5002     // Remember if this value is live-out.
5003     if (User->getOpcode() == ISD::CopyToReg)
5004       HasCopyToRegUses = true;
5005   }
5006
5007   if (HasCopyToRegUses) {
5008     bool BothLiveOut = false;
5009     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
5010          UI != UE; ++UI) {
5011       SDUse &Use = UI.getUse();
5012       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
5013         BothLiveOut = true;
5014         break;
5015       }
5016     }
5017     if (BothLiveOut)
5018       // Both unextended and extended values are live out. There had better be
5019       // a good reason for the transformation.
5020       return ExtendNodes.size();
5021   }
5022   return true;
5023 }
5024
5025 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
5026                                   SDValue Trunc, SDValue ExtLoad, SDLoc DL,
5027                                   ISD::NodeType ExtType) {
5028   // Extend SetCC uses if necessary.
5029   for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
5030     SDNode *SetCC = SetCCs[i];
5031     SmallVector<SDValue, 4> Ops;
5032
5033     for (unsigned j = 0; j != 2; ++j) {
5034       SDValue SOp = SetCC->getOperand(j);
5035       if (SOp == Trunc)
5036         Ops.push_back(ExtLoad);
5037       else
5038         Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
5039     }
5040
5041     Ops.push_back(SetCC->getOperand(2));
5042     CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
5043   }
5044 }
5045
5046 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
5047   SDValue N0 = N->getOperand(0);
5048   EVT VT = N->getValueType(0);
5049
5050   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5051                                               LegalOperations))
5052     return SDValue(Res, 0);
5053
5054   // fold (sext (sext x)) -> (sext x)
5055   // fold (sext (aext x)) -> (sext x)
5056   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5057     return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
5058                        N0.getOperand(0));
5059
5060   if (N0.getOpcode() == ISD::TRUNCATE) {
5061     // fold (sext (truncate (load x))) -> (sext (smaller load x))
5062     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
5063     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5064     if (NarrowLoad.getNode()) {
5065       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5066       if (NarrowLoad.getNode() != N0.getNode()) {
5067         CombineTo(N0.getNode(), NarrowLoad);
5068         // CombineTo deleted the truncate, if needed, but not what's under it.
5069         AddToWorklist(oye);
5070       }
5071       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5072     }
5073
5074     // See if the value being truncated is already sign extended.  If so, just
5075     // eliminate the trunc/sext pair.
5076     SDValue Op = N0.getOperand(0);
5077     unsigned OpBits   = Op.getValueType().getScalarType().getSizeInBits();
5078     unsigned MidBits  = N0.getValueType().getScalarType().getSizeInBits();
5079     unsigned DestBits = VT.getScalarType().getSizeInBits();
5080     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
5081
5082     if (OpBits == DestBits) {
5083       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
5084       // bits, it is already ready.
5085       if (NumSignBits > DestBits-MidBits)
5086         return Op;
5087     } else if (OpBits < DestBits) {
5088       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
5089       // bits, just sext from i32.
5090       if (NumSignBits > OpBits-MidBits)
5091         return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
5092     } else {
5093       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
5094       // bits, just truncate to i32.
5095       if (NumSignBits > OpBits-MidBits)
5096         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5097     }
5098
5099     // fold (sext (truncate x)) -> (sextinreg x).
5100     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
5101                                                  N0.getValueType())) {
5102       if (OpBits < DestBits)
5103         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
5104       else if (OpBits > DestBits)
5105         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
5106       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
5107                          DAG.getValueType(N0.getValueType()));
5108     }
5109   }
5110
5111   // fold (sext (load x)) -> (sext (truncate (sextload x)))
5112   // None of the supported targets knows how to perform load and sign extend
5113   // on vectors in one instruction.  We only perform this transformation on
5114   // scalars.
5115   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5116       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5117       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5118        TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
5119     bool DoXform = true;
5120     SmallVector<SDNode*, 4> SetCCs;
5121     if (!N0.hasOneUse())
5122       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
5123     if (DoXform) {
5124       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5125       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5126                                        LN0->getChain(),
5127                                        LN0->getBasePtr(), N0.getValueType(),
5128                                        LN0->getMemOperand());
5129       CombineTo(N, ExtLoad);
5130       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5131                                   N0.getValueType(), ExtLoad);
5132       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5133       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5134                       ISD::SIGN_EXTEND);
5135       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5136     }
5137   }
5138
5139   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
5140   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
5141   if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5142       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5143     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5144     EVT MemVT = LN0->getMemoryVT();
5145     if ((!LegalOperations && !LN0->isVolatile()) ||
5146         TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
5147       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5148                                        LN0->getChain(),
5149                                        LN0->getBasePtr(), MemVT,
5150                                        LN0->getMemOperand());
5151       CombineTo(N, ExtLoad);
5152       CombineTo(N0.getNode(),
5153                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5154                             N0.getValueType(), ExtLoad),
5155                 ExtLoad.getValue(1));
5156       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5157     }
5158   }
5159
5160   // fold (sext (and/or/xor (load x), cst)) ->
5161   //      (and/or/xor (sextload x), (sext cst))
5162   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5163        N0.getOpcode() == ISD::XOR) &&
5164       isa<LoadSDNode>(N0.getOperand(0)) &&
5165       N0.getOperand(1).getOpcode() == ISD::Constant &&
5166       TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) &&
5167       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5168     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5169     if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
5170       bool DoXform = true;
5171       SmallVector<SDNode*, 4> SetCCs;
5172       if (!N0.hasOneUse())
5173         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
5174                                           SetCCs, TLI);
5175       if (DoXform) {
5176         SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
5177                                          LN0->getChain(), LN0->getBasePtr(),
5178                                          LN0->getMemoryVT(),
5179                                          LN0->getMemOperand());
5180         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5181         Mask = Mask.sext(VT.getSizeInBits());
5182         SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5183                                   ExtLoad, DAG.getConstant(Mask, VT));
5184         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5185                                     SDLoc(N0.getOperand(0)),
5186                                     N0.getOperand(0).getValueType(), ExtLoad);
5187         CombineTo(N, And);
5188         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5189         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5190                         ISD::SIGN_EXTEND);
5191         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5192       }
5193     }
5194   }
5195
5196   if (N0.getOpcode() == ISD::SETCC) {
5197     EVT N0VT = N0.getOperand(0).getValueType();
5198     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
5199     // Only do this before legalize for now.
5200     if (VT.isVector() && !LegalOperations &&
5201         TLI.getBooleanContents(N0VT) ==
5202             TargetLowering::ZeroOrNegativeOneBooleanContent) {
5203       // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5204       // of the same size as the compared operands. Only optimize sext(setcc())
5205       // if this is the case.
5206       EVT SVT = getSetCCResultType(N0VT);
5207
5208       // We know that the # elements of the results is the same as the
5209       // # elements of the compare (and the # elements of the compare result
5210       // for that matter).  Check to see that they are the same size.  If so,
5211       // we know that the element size of the sext'd result matches the
5212       // element size of the compare operands.
5213       if (VT.getSizeInBits() == SVT.getSizeInBits())
5214         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5215                              N0.getOperand(1),
5216                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
5217
5218       // If the desired elements are smaller or larger than the source
5219       // elements we can use a matching integer vector type and then
5220       // truncate/sign extend
5221       EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5222       if (SVT == MatchingVectorType) {
5223         SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
5224                                N0.getOperand(0), N0.getOperand(1),
5225                                cast<CondCodeSDNode>(N0.getOperand(2))->get());
5226         return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5227       }
5228     }
5229
5230     // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
5231     unsigned ElementWidth = VT.getScalarType().getSizeInBits();
5232     SDValue NegOne =
5233       DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
5234     SDValue SCC =
5235       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5236                        NegOne, DAG.getConstant(0, VT),
5237                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5238     if (SCC.getNode()) return SCC;
5239
5240     if (!VT.isVector()) {
5241       EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
5242       if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
5243         SDLoc DL(N);
5244         ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5245         SDValue SetCC = DAG.getSetCC(DL, SetCCVT,
5246                                      N0.getOperand(0), N0.getOperand(1), CC);
5247         return DAG.getSelect(DL, VT, SetCC,
5248                              NegOne, DAG.getConstant(0, VT));
5249       }
5250     }
5251   }
5252
5253   // fold (sext x) -> (zext x) if the sign bit is known zero.
5254   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
5255       DAG.SignBitIsZero(N0))
5256     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
5257
5258   return SDValue();
5259 }
5260
5261 // isTruncateOf - If N is a truncate of some other value, return true, record
5262 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
5263 // This function computes KnownZero to avoid a duplicated call to
5264 // computeKnownBits in the caller.
5265 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
5266                          APInt &KnownZero) {
5267   APInt KnownOne;
5268   if (N->getOpcode() == ISD::TRUNCATE) {
5269     Op = N->getOperand(0);
5270     DAG.computeKnownBits(Op, KnownZero, KnownOne);
5271     return true;
5272   }
5273
5274   if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
5275       cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
5276     return false;
5277
5278   SDValue Op0 = N->getOperand(0);
5279   SDValue Op1 = N->getOperand(1);
5280   assert(Op0.getValueType() == Op1.getValueType());
5281
5282   ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
5283   ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
5284   if (COp0 && COp0->isNullValue())
5285     Op = Op1;
5286   else if (COp1 && COp1->isNullValue())
5287     Op = Op0;
5288   else
5289     return false;
5290
5291   DAG.computeKnownBits(Op, KnownZero, KnownOne);
5292
5293   if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
5294     return false;
5295
5296   return true;
5297 }
5298
5299 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
5300   SDValue N0 = N->getOperand(0);
5301   EVT VT = N->getValueType(0);
5302
5303   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5304                                               LegalOperations))
5305     return SDValue(Res, 0);
5306
5307   // fold (zext (zext x)) -> (zext x)
5308   // fold (zext (aext x)) -> (zext x)
5309   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5310     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
5311                        N0.getOperand(0));
5312
5313   // fold (zext (truncate x)) -> (zext x) or
5314   //      (zext (truncate x)) -> (truncate x)
5315   // This is valid when the truncated bits of x are already zero.
5316   // FIXME: We should extend this to work for vectors too.
5317   SDValue Op;
5318   APInt KnownZero;
5319   if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
5320     APInt TruncatedBits =
5321       (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
5322       APInt(Op.getValueSizeInBits(), 0) :
5323       APInt::getBitsSet(Op.getValueSizeInBits(),
5324                         N0.getValueSizeInBits(),
5325                         std::min(Op.getValueSizeInBits(),
5326                                  VT.getSizeInBits()));
5327     if (TruncatedBits == (KnownZero & TruncatedBits)) {
5328       if (VT.bitsGT(Op.getValueType()))
5329         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
5330       if (VT.bitsLT(Op.getValueType()))
5331         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5332
5333       return Op;
5334     }
5335   }
5336
5337   // fold (zext (truncate (load x))) -> (zext (smaller load x))
5338   // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
5339   if (N0.getOpcode() == ISD::TRUNCATE) {
5340     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5341     if (NarrowLoad.getNode()) {
5342       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5343       if (NarrowLoad.getNode() != N0.getNode()) {
5344         CombineTo(N0.getNode(), NarrowLoad);
5345         // CombineTo deleted the truncate, if needed, but not what's under it.
5346         AddToWorklist(oye);
5347       }
5348       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5349     }
5350   }
5351
5352   // fold (zext (truncate x)) -> (and x, mask)
5353   if (N0.getOpcode() == ISD::TRUNCATE &&
5354       (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
5355
5356     // fold (zext (truncate (load x))) -> (zext (smaller load x))
5357     // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
5358     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5359     if (NarrowLoad.getNode()) {
5360       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5361       if (NarrowLoad.getNode() != N0.getNode()) {
5362         CombineTo(N0.getNode(), NarrowLoad);
5363         // CombineTo deleted the truncate, if needed, but not what's under it.
5364         AddToWorklist(oye);
5365       }
5366       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5367     }
5368
5369     SDValue Op = N0.getOperand(0);
5370     if (Op.getValueType().bitsLT(VT)) {
5371       Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
5372       AddToWorklist(Op.getNode());
5373     } else if (Op.getValueType().bitsGT(VT)) {
5374       Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5375       AddToWorklist(Op.getNode());
5376     }
5377     return DAG.getZeroExtendInReg(Op, SDLoc(N),
5378                                   N0.getValueType().getScalarType());
5379   }
5380
5381   // Fold (zext (and (trunc x), cst)) -> (and x, cst),
5382   // if either of the casts is not free.
5383   if (N0.getOpcode() == ISD::AND &&
5384       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5385       N0.getOperand(1).getOpcode() == ISD::Constant &&
5386       (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5387                            N0.getValueType()) ||
5388        !TLI.isZExtFree(N0.getValueType(), VT))) {
5389     SDValue X = N0.getOperand(0).getOperand(0);
5390     if (X.getValueType().bitsLT(VT)) {
5391       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
5392     } else if (X.getValueType().bitsGT(VT)) {
5393       X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
5394     }
5395     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5396     Mask = Mask.zext(VT.getSizeInBits());
5397     return DAG.getNode(ISD::AND, SDLoc(N), VT,
5398                        X, DAG.getConstant(Mask, VT));
5399   }
5400
5401   // fold (zext (load x)) -> (zext (truncate (zextload x)))
5402   // None of the supported targets knows how to perform load and vector_zext
5403   // on vectors in one instruction.  We only perform this transformation on
5404   // scalars.
5405   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5406       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5407       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5408        TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
5409     bool DoXform = true;
5410     SmallVector<SDNode*, 4> SetCCs;
5411     if (!N0.hasOneUse())
5412       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
5413     if (DoXform) {
5414       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5415       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5416                                        LN0->getChain(),
5417                                        LN0->getBasePtr(), N0.getValueType(),
5418                                        LN0->getMemOperand());
5419       CombineTo(N, ExtLoad);
5420       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5421                                   N0.getValueType(), ExtLoad);
5422       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5423
5424       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5425                       ISD::ZERO_EXTEND);
5426       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5427     }
5428   }
5429
5430   // fold (zext (and/or/xor (load x), cst)) ->
5431   //      (and/or/xor (zextload x), (zext cst))
5432   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5433        N0.getOpcode() == ISD::XOR) &&
5434       isa<LoadSDNode>(N0.getOperand(0)) &&
5435       N0.getOperand(1).getOpcode() == ISD::Constant &&
5436       TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) &&
5437       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5438     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5439     if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
5440       bool DoXform = true;
5441       SmallVector<SDNode*, 4> SetCCs;
5442       if (!N0.hasOneUse())
5443         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
5444                                           SetCCs, TLI);
5445       if (DoXform) {
5446         SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
5447                                          LN0->getChain(), LN0->getBasePtr(),
5448                                          LN0->getMemoryVT(),
5449                                          LN0->getMemOperand());
5450         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5451         Mask = Mask.zext(VT.getSizeInBits());
5452         SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5453                                   ExtLoad, DAG.getConstant(Mask, VT));
5454         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5455                                     SDLoc(N0.getOperand(0)),
5456                                     N0.getOperand(0).getValueType(), ExtLoad);
5457         CombineTo(N, And);
5458         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5459         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5460                         ISD::ZERO_EXTEND);
5461         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5462       }
5463     }
5464   }
5465
5466   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
5467   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
5468   if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5469       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5470     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5471     EVT MemVT = LN0->getMemoryVT();
5472     if ((!LegalOperations && !LN0->isVolatile()) ||
5473         TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
5474       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5475                                        LN0->getChain(),
5476                                        LN0->getBasePtr(), MemVT,
5477                                        LN0->getMemOperand());
5478       CombineTo(N, ExtLoad);
5479       CombineTo(N0.getNode(),
5480                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
5481                             ExtLoad),
5482                 ExtLoad.getValue(1));
5483       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5484     }
5485   }
5486
5487   if (N0.getOpcode() == ISD::SETCC) {
5488     if (!LegalOperations && VT.isVector() &&
5489         N0.getValueType().getVectorElementType() == MVT::i1) {
5490       EVT N0VT = N0.getOperand(0).getValueType();
5491       if (getSetCCResultType(N0VT) == N0.getValueType())
5492         return SDValue();
5493
5494       // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
5495       // Only do this before legalize for now.
5496       EVT EltVT = VT.getVectorElementType();
5497       SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
5498                                     DAG.getConstant(1, EltVT));
5499       if (VT.getSizeInBits() == N0VT.getSizeInBits())
5500         // We know that the # elements of the results is the same as the
5501         // # elements of the compare (and the # elements of the compare result
5502         // for that matter).  Check to see that they are the same size.  If so,
5503         // we know that the element size of the sext'd result matches the
5504         // element size of the compare operands.
5505         return DAG.getNode(ISD::AND, SDLoc(N), VT,
5506                            DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5507                                          N0.getOperand(1),
5508                                  cast<CondCodeSDNode>(N0.getOperand(2))->get()),
5509                            DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
5510                                        OneOps));
5511
5512       // If the desired elements are smaller or larger than the source
5513       // elements we can use a matching integer vector type and then
5514       // truncate/sign extend
5515       EVT MatchingElementType =
5516         EVT::getIntegerVT(*DAG.getContext(),
5517                           N0VT.getScalarType().getSizeInBits());
5518       EVT MatchingVectorType =
5519         EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5520                          N0VT.getVectorNumElements());
5521       SDValue VsetCC =
5522         DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5523                       N0.getOperand(1),
5524                       cast<CondCodeSDNode>(N0.getOperand(2))->get());
5525       return DAG.getNode(ISD::AND, SDLoc(N), VT,
5526                          DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
5527                          DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, OneOps));
5528     }
5529
5530     // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5531     SDValue SCC =
5532       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5533                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5534                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5535     if (SCC.getNode()) return SCC;
5536   }
5537
5538   // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
5539   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
5540       isa<ConstantSDNode>(N0.getOperand(1)) &&
5541       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
5542       N0.hasOneUse()) {
5543     SDValue ShAmt = N0.getOperand(1);
5544     unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
5545     if (N0.getOpcode() == ISD::SHL) {
5546       SDValue InnerZExt = N0.getOperand(0);
5547       // If the original shl may be shifting out bits, do not perform this
5548       // transformation.
5549       unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
5550         InnerZExt.getOperand(0).getValueType().getSizeInBits();
5551       if (ShAmtVal > KnownZeroBits)
5552         return SDValue();
5553     }
5554
5555     SDLoc DL(N);
5556
5557     // Ensure that the shift amount is wide enough for the shifted value.
5558     if (VT.getSizeInBits() >= 256)
5559       ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
5560
5561     return DAG.getNode(N0.getOpcode(), DL, VT,
5562                        DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
5563                        ShAmt);
5564   }
5565
5566   return SDValue();
5567 }
5568
5569 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
5570   SDValue N0 = N->getOperand(0);
5571   EVT VT = N->getValueType(0);
5572
5573   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5574                                               LegalOperations))
5575     return SDValue(Res, 0);
5576
5577   // fold (aext (aext x)) -> (aext x)
5578   // fold (aext (zext x)) -> (zext x)
5579   // fold (aext (sext x)) -> (sext x)
5580   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
5581       N0.getOpcode() == ISD::ZERO_EXTEND ||
5582       N0.getOpcode() == ISD::SIGN_EXTEND)
5583     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
5584
5585   // fold (aext (truncate (load x))) -> (aext (smaller load x))
5586   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
5587   if (N0.getOpcode() == ISD::TRUNCATE) {
5588     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5589     if (NarrowLoad.getNode()) {
5590       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5591       if (NarrowLoad.getNode() != N0.getNode()) {
5592         CombineTo(N0.getNode(), NarrowLoad);
5593         // CombineTo deleted the truncate, if needed, but not what's under it.
5594         AddToWorklist(oye);
5595       }
5596       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5597     }
5598   }
5599
5600   // fold (aext (truncate x))
5601   if (N0.getOpcode() == ISD::TRUNCATE) {
5602     SDValue TruncOp = N0.getOperand(0);
5603     if (TruncOp.getValueType() == VT)
5604       return TruncOp; // x iff x size == zext size.
5605     if (TruncOp.getValueType().bitsGT(VT))
5606       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
5607     return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
5608   }
5609
5610   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
5611   // if the trunc is not free.
5612   if (N0.getOpcode() == ISD::AND &&
5613       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5614       N0.getOperand(1).getOpcode() == ISD::Constant &&
5615       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5616                           N0.getValueType())) {
5617     SDValue X = N0.getOperand(0).getOperand(0);
5618     if (X.getValueType().bitsLT(VT)) {
5619       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
5620     } else if (X.getValueType().bitsGT(VT)) {
5621       X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
5622     }
5623     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5624     Mask = Mask.zext(VT.getSizeInBits());
5625     return DAG.getNode(ISD::AND, SDLoc(N), VT,
5626                        X, DAG.getConstant(Mask, VT));
5627   }
5628
5629   // fold (aext (load x)) -> (aext (truncate (extload x)))
5630   // None of the supported targets knows how to perform load and any_ext
5631   // on vectors in one instruction.  We only perform this transformation on
5632   // scalars.
5633   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5634       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5635       TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType())) {
5636     bool DoXform = true;
5637     SmallVector<SDNode*, 4> SetCCs;
5638     if (!N0.hasOneUse())
5639       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
5640     if (DoXform) {
5641       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5642       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
5643                                        LN0->getChain(),
5644                                        LN0->getBasePtr(), N0.getValueType(),
5645                                        LN0->getMemOperand());
5646       CombineTo(N, ExtLoad);
5647       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5648                                   N0.getValueType(), ExtLoad);
5649       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5650       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5651                       ISD::ANY_EXTEND);
5652       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5653     }
5654   }
5655
5656   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
5657   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
5658   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
5659   if (N0.getOpcode() == ISD::LOAD &&
5660       !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5661       N0.hasOneUse()) {
5662     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5663     ISD::LoadExtType ExtType = LN0->getExtensionType();
5664     EVT MemVT = LN0->getMemoryVT();
5665     if (!LegalOperations || TLI.isLoadExtLegal(ExtType, MemVT)) {
5666       SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
5667                                        VT, LN0->getChain(), LN0->getBasePtr(),
5668                                        MemVT, LN0->getMemOperand());
5669       CombineTo(N, ExtLoad);
5670       CombineTo(N0.getNode(),
5671                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5672                             N0.getValueType(), ExtLoad),
5673                 ExtLoad.getValue(1));
5674       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5675     }
5676   }
5677
5678   if (N0.getOpcode() == ISD::SETCC) {
5679     // For vectors:
5680     // aext(setcc) -> vsetcc
5681     // aext(setcc) -> truncate(vsetcc)
5682     // aext(setcc) -> aext(vsetcc)
5683     // Only do this before legalize for now.
5684     if (VT.isVector() && !LegalOperations) {
5685       EVT N0VT = N0.getOperand(0).getValueType();
5686         // We know that the # elements of the results is the same as the
5687         // # elements of the compare (and the # elements of the compare result
5688         // for that matter).  Check to see that they are the same size.  If so,
5689         // we know that the element size of the sext'd result matches the
5690         // element size of the compare operands.
5691       if (VT.getSizeInBits() == N0VT.getSizeInBits())
5692         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5693                              N0.getOperand(1),
5694                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
5695       // If the desired elements are smaller or larger than the source
5696       // elements we can use a matching integer vector type and then
5697       // truncate/any extend
5698       else {
5699         EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5700         SDValue VsetCC =
5701           DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5702                         N0.getOperand(1),
5703                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
5704         return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
5705       }
5706     }
5707
5708     // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5709     SDValue SCC =
5710       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5711                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5712                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5713     if (SCC.getNode())
5714       return SCC;
5715   }
5716
5717   return SDValue();
5718 }
5719
5720 /// See if the specified operand can be simplified with the knowledge that only
5721 /// the bits specified by Mask are used.  If so, return the simpler operand,
5722 /// otherwise return a null SDValue.
5723 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
5724   switch (V.getOpcode()) {
5725   default: break;
5726   case ISD::Constant: {
5727     const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
5728     assert(CV && "Const value should be ConstSDNode.");
5729     const APInt &CVal = CV->getAPIntValue();
5730     APInt NewVal = CVal & Mask;
5731     if (NewVal != CVal)
5732       return DAG.getConstant(NewVal, V.getValueType());
5733     break;
5734   }
5735   case ISD::OR:
5736   case ISD::XOR:
5737     // If the LHS or RHS don't contribute bits to the or, drop them.
5738     if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
5739       return V.getOperand(1);
5740     if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
5741       return V.getOperand(0);
5742     break;
5743   case ISD::SRL:
5744     // Only look at single-use SRLs.
5745     if (!V.getNode()->hasOneUse())
5746       break;
5747     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
5748       // See if we can recursively simplify the LHS.
5749       unsigned Amt = RHSC->getZExtValue();
5750
5751       // Watch out for shift count overflow though.
5752       if (Amt >= Mask.getBitWidth()) break;
5753       APInt NewMask = Mask << Amt;
5754       SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
5755       if (SimplifyLHS.getNode())
5756         return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
5757                            SimplifyLHS, V.getOperand(1));
5758     }
5759   }
5760   return SDValue();
5761 }
5762
5763 /// If the result of a wider load is shifted to right of N  bits and then
5764 /// truncated to a narrower type and where N is a multiple of number of bits of
5765 /// the narrower type, transform it to a narrower load from address + N / num of
5766 /// bits of new type. If the result is to be extended, also fold the extension
5767 /// to form a extending load.
5768 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
5769   unsigned Opc = N->getOpcode();
5770
5771   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
5772   SDValue N0 = N->getOperand(0);
5773   EVT VT = N->getValueType(0);
5774   EVT ExtVT = VT;
5775
5776   // This transformation isn't valid for vector loads.
5777   if (VT.isVector())
5778     return SDValue();
5779
5780   // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
5781   // extended to VT.
5782   if (Opc == ISD::SIGN_EXTEND_INREG) {
5783     ExtType = ISD::SEXTLOAD;
5784     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
5785   } else if (Opc == ISD::SRL) {
5786     // Another special-case: SRL is basically zero-extending a narrower value.
5787     ExtType = ISD::ZEXTLOAD;
5788     N0 = SDValue(N, 0);
5789     ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5790     if (!N01) return SDValue();
5791     ExtVT = EVT::getIntegerVT(*DAG.getContext(),
5792                               VT.getSizeInBits() - N01->getZExtValue());
5793   }
5794   if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT))
5795     return SDValue();
5796
5797   unsigned EVTBits = ExtVT.getSizeInBits();
5798
5799   // Do not generate loads of non-round integer types since these can
5800   // be expensive (and would be wrong if the type is not byte sized).
5801   if (!ExtVT.isRound())
5802     return SDValue();
5803
5804   unsigned ShAmt = 0;
5805   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
5806     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5807       ShAmt = N01->getZExtValue();
5808       // Is the shift amount a multiple of size of VT?
5809       if ((ShAmt & (EVTBits-1)) == 0) {
5810         N0 = N0.getOperand(0);
5811         // Is the load width a multiple of size of VT?
5812         if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
5813           return SDValue();
5814       }
5815
5816       // At this point, we must have a load or else we can't do the transform.
5817       if (!isa<LoadSDNode>(N0)) return SDValue();
5818
5819       // Because a SRL must be assumed to *need* to zero-extend the high bits
5820       // (as opposed to anyext the high bits), we can't combine the zextload
5821       // lowering of SRL and an sextload.
5822       if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
5823         return SDValue();
5824
5825       // If the shift amount is larger than the input type then we're not
5826       // accessing any of the loaded bytes.  If the load was a zextload/extload
5827       // then the result of the shift+trunc is zero/undef (handled elsewhere).
5828       if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
5829         return SDValue();
5830     }
5831   }
5832
5833   // If the load is shifted left (and the result isn't shifted back right),
5834   // we can fold the truncate through the shift.
5835   unsigned ShLeftAmt = 0;
5836   if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
5837       ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
5838     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5839       ShLeftAmt = N01->getZExtValue();
5840       N0 = N0.getOperand(0);
5841     }
5842   }
5843
5844   // If we haven't found a load, we can't narrow it.  Don't transform one with
5845   // multiple uses, this would require adding a new load.
5846   if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
5847     return SDValue();
5848
5849   // Don't change the width of a volatile load.
5850   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5851   if (LN0->isVolatile())
5852     return SDValue();
5853
5854   // Verify that we are actually reducing a load width here.
5855   if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
5856     return SDValue();
5857
5858   // For the transform to be legal, the load must produce only two values
5859   // (the value loaded and the chain).  Don't transform a pre-increment
5860   // load, for example, which produces an extra value.  Otherwise the
5861   // transformation is not equivalent, and the downstream logic to replace
5862   // uses gets things wrong.
5863   if (LN0->getNumValues() > 2)
5864     return SDValue();
5865
5866   // If the load that we're shrinking is an extload and we're not just
5867   // discarding the extension we can't simply shrink the load. Bail.
5868   // TODO: It would be possible to merge the extensions in some cases.
5869   if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
5870       LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
5871     return SDValue();
5872
5873   EVT PtrType = N0.getOperand(1).getValueType();
5874
5875   if (PtrType == MVT::Untyped || PtrType.isExtended())
5876     // It's not possible to generate a constant of extended or untyped type.
5877     return SDValue();
5878
5879   // For big endian targets, we need to adjust the offset to the pointer to
5880   // load the correct bytes.
5881   if (TLI.isBigEndian()) {
5882     unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
5883     unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
5884     ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
5885   }
5886
5887   uint64_t PtrOff = ShAmt / 8;
5888   unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
5889   SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
5890                                PtrType, LN0->getBasePtr(),
5891                                DAG.getConstant(PtrOff, PtrType));
5892   AddToWorklist(NewPtr.getNode());
5893
5894   SDValue Load;
5895   if (ExtType == ISD::NON_EXTLOAD)
5896     Load =  DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
5897                         LN0->getPointerInfo().getWithOffset(PtrOff),
5898                         LN0->isVolatile(), LN0->isNonTemporal(),
5899                         LN0->isInvariant(), NewAlign, LN0->getAAInfo());
5900   else
5901     Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
5902                           LN0->getPointerInfo().getWithOffset(PtrOff),
5903                           ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
5904                           LN0->isInvariant(), NewAlign, LN0->getAAInfo());
5905
5906   // Replace the old load's chain with the new load's chain.
5907   WorklistRemover DeadNodes(*this);
5908   DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
5909
5910   // Shift the result left, if we've swallowed a left shift.
5911   SDValue Result = Load;
5912   if (ShLeftAmt != 0) {
5913     EVT ShImmTy = getShiftAmountTy(Result.getValueType());
5914     if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
5915       ShImmTy = VT;
5916     // If the shift amount is as large as the result size (but, presumably,
5917     // no larger than the source) then the useful bits of the result are
5918     // zero; we can't simply return the shortened shift, because the result
5919     // of that operation is undefined.
5920     if (ShLeftAmt >= VT.getSizeInBits())
5921       Result = DAG.getConstant(0, VT);
5922     else
5923       Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
5924                           Result, DAG.getConstant(ShLeftAmt, ShImmTy));
5925   }
5926
5927   // Return the new loaded value.
5928   return Result;
5929 }
5930
5931 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
5932   SDValue N0 = N->getOperand(0);
5933   SDValue N1 = N->getOperand(1);
5934   EVT VT = N->getValueType(0);
5935   EVT EVT = cast<VTSDNode>(N1)->getVT();
5936   unsigned VTBits = VT.getScalarType().getSizeInBits();
5937   unsigned EVTBits = EVT.getScalarType().getSizeInBits();
5938
5939   // fold (sext_in_reg c1) -> c1
5940   if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
5941     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
5942
5943   // If the input is already sign extended, just drop the extension.
5944   if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
5945     return N0;
5946
5947   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
5948   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
5949       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
5950     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5951                        N0.getOperand(0), N1);
5952
5953   // fold (sext_in_reg (sext x)) -> (sext x)
5954   // fold (sext_in_reg (aext x)) -> (sext x)
5955   // if x is small enough.
5956   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
5957     SDValue N00 = N0.getOperand(0);
5958     if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
5959         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
5960       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
5961   }
5962
5963   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
5964   if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
5965     return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
5966
5967   // fold operands of sext_in_reg based on knowledge that the top bits are not
5968   // demanded.
5969   if (SimplifyDemandedBits(SDValue(N, 0)))
5970     return SDValue(N, 0);
5971
5972   // fold (sext_in_reg (load x)) -> (smaller sextload x)
5973   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
5974   SDValue NarrowLoad = ReduceLoadWidth(N);
5975   if (NarrowLoad.getNode())
5976     return NarrowLoad;
5977
5978   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
5979   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
5980   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
5981   if (N0.getOpcode() == ISD::SRL) {
5982     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
5983       if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
5984         // We can turn this into an SRA iff the input to the SRL is already sign
5985         // extended enough.
5986         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
5987         if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
5988           return DAG.getNode(ISD::SRA, SDLoc(N), VT,
5989                              N0.getOperand(0), N0.getOperand(1));
5990       }
5991   }
5992
5993   // fold (sext_inreg (extload x)) -> (sextload x)
5994   if (ISD::isEXTLoad(N0.getNode()) &&
5995       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5996       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5997       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5998        TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5999     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6000     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6001                                      LN0->getChain(),
6002                                      LN0->getBasePtr(), EVT,
6003                                      LN0->getMemOperand());
6004     CombineTo(N, ExtLoad);
6005     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6006     AddToWorklist(ExtLoad.getNode());
6007     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6008   }
6009   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
6010   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6011       N0.hasOneUse() &&
6012       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6013       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6014        TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
6015     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6016     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6017                                      LN0->getChain(),
6018                                      LN0->getBasePtr(), EVT,
6019                                      LN0->getMemOperand());
6020     CombineTo(N, ExtLoad);
6021     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6022     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6023   }
6024
6025   // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
6026   if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
6027     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
6028                                        N0.getOperand(1), false);
6029     if (BSwap.getNode())
6030       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6031                          BSwap, N1);
6032   }
6033
6034   // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
6035   // into a build_vector.
6036   if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
6037     SmallVector<SDValue, 8> Elts;
6038     unsigned NumElts = N0->getNumOperands();
6039     unsigned ShAmt = VTBits - EVTBits;
6040
6041     for (unsigned i = 0; i != NumElts; ++i) {
6042       SDValue Op = N0->getOperand(i);
6043       if (Op->getOpcode() == ISD::UNDEF) {
6044         Elts.push_back(Op);
6045         continue;
6046       }
6047
6048       ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
6049       const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
6050       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
6051                                      Op.getValueType()));
6052     }
6053
6054     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts);
6055   }
6056
6057   return SDValue();
6058 }
6059
6060 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
6061   SDValue N0 = N->getOperand(0);
6062   EVT VT = N->getValueType(0);
6063   bool isLE = TLI.isLittleEndian();
6064
6065   // noop truncate
6066   if (N0.getValueType() == N->getValueType(0))
6067     return N0;
6068   // fold (truncate c1) -> c1
6069   if (isa<ConstantSDNode>(N0))
6070     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
6071   // fold (truncate (truncate x)) -> (truncate x)
6072   if (N0.getOpcode() == ISD::TRUNCATE)
6073     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6074   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
6075   if (N0.getOpcode() == ISD::ZERO_EXTEND ||
6076       N0.getOpcode() == ISD::SIGN_EXTEND ||
6077       N0.getOpcode() == ISD::ANY_EXTEND) {
6078     if (N0.getOperand(0).getValueType().bitsLT(VT))
6079       // if the source is smaller than the dest, we still need an extend
6080       return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
6081                          N0.getOperand(0));
6082     if (N0.getOperand(0).getValueType().bitsGT(VT))
6083       // if the source is larger than the dest, than we just need the truncate
6084       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6085     // if the source and dest are the same type, we can drop both the extend
6086     // and the truncate.
6087     return N0.getOperand(0);
6088   }
6089
6090   // Fold extract-and-trunc into a narrow extract. For example:
6091   //   i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
6092   //   i32 y = TRUNCATE(i64 x)
6093   //        -- becomes --
6094   //   v16i8 b = BITCAST (v2i64 val)
6095   //   i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
6096   //
6097   // Note: We only run this optimization after type legalization (which often
6098   // creates this pattern) and before operation legalization after which
6099   // we need to be more careful about the vector instructions that we generate.
6100   if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6101       LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
6102
6103     EVT VecTy = N0.getOperand(0).getValueType();
6104     EVT ExTy = N0.getValueType();
6105     EVT TrTy = N->getValueType(0);
6106
6107     unsigned NumElem = VecTy.getVectorNumElements();
6108     unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
6109
6110     EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
6111     assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
6112
6113     SDValue EltNo = N0->getOperand(1);
6114     if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
6115       int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6116       EVT IndexTy = TLI.getVectorIdxTy();
6117       int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
6118
6119       SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
6120                               NVT, N0.getOperand(0));
6121
6122       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
6123                          SDLoc(N), TrTy, V,
6124                          DAG.getConstant(Index, IndexTy));
6125     }
6126   }
6127
6128   // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
6129   if (N0.getOpcode() == ISD::SELECT) {
6130     EVT SrcVT = N0.getValueType();
6131     if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
6132         TLI.isTruncateFree(SrcVT, VT)) {
6133       SDLoc SL(N0);
6134       SDValue Cond = N0.getOperand(0);
6135       SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
6136       SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
6137       return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
6138     }
6139   }
6140
6141   // Fold a series of buildvector, bitcast, and truncate if possible.
6142   // For example fold
6143   //   (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
6144   //   (2xi32 (buildvector x, y)).
6145   if (Level == AfterLegalizeVectorOps && VT.isVector() &&
6146       N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
6147       N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
6148       N0.getOperand(0).hasOneUse()) {
6149
6150     SDValue BuildVect = N0.getOperand(0);
6151     EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
6152     EVT TruncVecEltTy = VT.getVectorElementType();
6153
6154     // Check that the element types match.
6155     if (BuildVectEltTy == TruncVecEltTy) {
6156       // Now we only need to compute the offset of the truncated elements.
6157       unsigned BuildVecNumElts =  BuildVect.getNumOperands();
6158       unsigned TruncVecNumElts = VT.getVectorNumElements();
6159       unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
6160
6161       assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
6162              "Invalid number of elements");
6163
6164       SmallVector<SDValue, 8> Opnds;
6165       for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
6166         Opnds.push_back(BuildVect.getOperand(i));
6167
6168       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
6169     }
6170   }
6171
6172   // See if we can simplify the input to this truncate through knowledge that
6173   // only the low bits are being used.
6174   // For example "trunc (or (shl x, 8), y)" // -> trunc y
6175   // Currently we only perform this optimization on scalars because vectors
6176   // may have different active low bits.
6177   if (!VT.isVector()) {
6178     SDValue Shorter =
6179       GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
6180                                                VT.getSizeInBits()));
6181     if (Shorter.getNode())
6182       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
6183   }
6184   // fold (truncate (load x)) -> (smaller load x)
6185   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
6186   if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
6187     SDValue Reduced = ReduceLoadWidth(N);
6188     if (Reduced.getNode())
6189       return Reduced;
6190     // Handle the case where the load remains an extending load even
6191     // after truncation.
6192     if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
6193       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6194       if (!LN0->isVolatile() &&
6195           LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
6196         SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
6197                                          VT, LN0->getChain(), LN0->getBasePtr(),
6198                                          LN0->getMemoryVT(),
6199                                          LN0->getMemOperand());
6200         DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
6201         return NewLoad;
6202       }
6203     }
6204   }
6205   // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
6206   // where ... are all 'undef'.
6207   if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
6208     SmallVector<EVT, 8> VTs;
6209     SDValue V;
6210     unsigned Idx = 0;
6211     unsigned NumDefs = 0;
6212
6213     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
6214       SDValue X = N0.getOperand(i);
6215       if (X.getOpcode() != ISD::UNDEF) {
6216         V = X;
6217         Idx = i;
6218         NumDefs++;
6219       }
6220       // Stop if more than one members are non-undef.
6221       if (NumDefs > 1)
6222         break;
6223       VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
6224                                      VT.getVectorElementType(),
6225                                      X.getValueType().getVectorNumElements()));
6226     }
6227
6228     if (NumDefs == 0)
6229       return DAG.getUNDEF(VT);
6230
6231     if (NumDefs == 1) {
6232       assert(V.getNode() && "The single defined operand is empty!");
6233       SmallVector<SDValue, 8> Opnds;
6234       for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
6235         if (i != Idx) {
6236           Opnds.push_back(DAG.getUNDEF(VTs[i]));
6237           continue;
6238         }
6239         SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
6240         AddToWorklist(NV.getNode());
6241         Opnds.push_back(NV);
6242       }
6243       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
6244     }
6245   }
6246
6247   // Simplify the operands using demanded-bits information.
6248   if (!VT.isVector() &&
6249       SimplifyDemandedBits(SDValue(N, 0)))
6250     return SDValue(N, 0);
6251
6252   return SDValue();
6253 }
6254
6255 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
6256   SDValue Elt = N->getOperand(i);
6257   if (Elt.getOpcode() != ISD::MERGE_VALUES)
6258     return Elt.getNode();
6259   return Elt.getOperand(Elt.getResNo()).getNode();
6260 }
6261
6262 /// build_pair (load, load) -> load
6263 /// if load locations are consecutive.
6264 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
6265   assert(N->getOpcode() == ISD::BUILD_PAIR);
6266
6267   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
6268   LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
6269   if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
6270       LD1->getAddressSpace() != LD2->getAddressSpace())
6271     return SDValue();
6272   EVT LD1VT = LD1->getValueType(0);
6273
6274   if (ISD::isNON_EXTLoad(LD2) &&
6275       LD2->hasOneUse() &&
6276       // If both are volatile this would reduce the number of volatile loads.
6277       // If one is volatile it might be ok, but play conservative and bail out.
6278       !LD1->isVolatile() &&
6279       !LD2->isVolatile() &&
6280       DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
6281     unsigned Align = LD1->getAlignment();
6282     unsigned NewAlign = TLI.getDataLayout()->
6283       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6284
6285     if (NewAlign <= Align &&
6286         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
6287       return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
6288                          LD1->getBasePtr(), LD1->getPointerInfo(),
6289                          false, false, false, Align);
6290   }
6291
6292   return SDValue();
6293 }
6294
6295 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
6296   SDValue N0 = N->getOperand(0);
6297   EVT VT = N->getValueType(0);
6298
6299   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
6300   // Only do this before legalize, since afterward the target may be depending
6301   // on the bitconvert.
6302   // First check to see if this is all constant.
6303   if (!LegalTypes &&
6304       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
6305       VT.isVector()) {
6306     bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
6307
6308     EVT DestEltVT = N->getValueType(0).getVectorElementType();
6309     assert(!DestEltVT.isVector() &&
6310            "Element type of vector ValueType must not be vector!");
6311     if (isSimple)
6312       return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
6313   }
6314
6315   // If the input is a constant, let getNode fold it.
6316   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
6317     SDValue Res = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
6318     if (Res.getNode() != N) {
6319       if (!LegalOperations ||
6320           TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
6321         return Res;
6322
6323       // Folding it resulted in an illegal node, and it's too late to
6324       // do that. Clean up the old node and forego the transformation.
6325       // Ideally this won't happen very often, because instcombine
6326       // and the earlier dagcombine runs (where illegal nodes are
6327       // permitted) should have folded most of them already.
6328       deleteAndRecombine(Res.getNode());
6329     }
6330   }
6331
6332   // (conv (conv x, t1), t2) -> (conv x, t2)
6333   if (N0.getOpcode() == ISD::BITCAST)
6334     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
6335                        N0.getOperand(0));
6336
6337   // fold (conv (load x)) -> (load (conv*)x)
6338   // If the resultant load doesn't need a higher alignment than the original!
6339   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
6340       // Do not change the width of a volatile load.
6341       !cast<LoadSDNode>(N0)->isVolatile() &&
6342       // Do not remove the cast if the types differ in endian layout.
6343       TLI.hasBigEndianPartOrdering(N0.getValueType()) ==
6344       TLI.hasBigEndianPartOrdering(VT) &&
6345       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
6346       TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
6347     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6348     unsigned Align = TLI.getDataLayout()->
6349       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6350     unsigned OrigAlign = LN0->getAlignment();
6351
6352     if (Align <= OrigAlign) {
6353       SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
6354                                  LN0->getBasePtr(), LN0->getPointerInfo(),
6355                                  LN0->isVolatile(), LN0->isNonTemporal(),
6356                                  LN0->isInvariant(), OrigAlign,
6357                                  LN0->getAAInfo());
6358       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6359       return Load;
6360     }
6361   }
6362
6363   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6364   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
6365   // This often reduces constant pool loads.
6366   if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
6367        (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
6368       N0.getNode()->hasOneUse() && VT.isInteger() &&
6369       !VT.isVector() && !N0.getValueType().isVector()) {
6370     SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
6371                                   N0.getOperand(0));
6372     AddToWorklist(NewConv.getNode());
6373
6374     APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6375     if (N0.getOpcode() == ISD::FNEG)
6376       return DAG.getNode(ISD::XOR, SDLoc(N), VT,
6377                          NewConv, DAG.getConstant(SignBit, VT));
6378     assert(N0.getOpcode() == ISD::FABS);
6379     return DAG.getNode(ISD::AND, SDLoc(N), VT,
6380                        NewConv, DAG.getConstant(~SignBit, VT));
6381   }
6382
6383   // fold (bitconvert (fcopysign cst, x)) ->
6384   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
6385   // Note that we don't handle (copysign x, cst) because this can always be
6386   // folded to an fneg or fabs.
6387   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
6388       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
6389       VT.isInteger() && !VT.isVector()) {
6390     unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
6391     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
6392     if (isTypeLegal(IntXVT)) {
6393       SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6394                               IntXVT, N0.getOperand(1));
6395       AddToWorklist(X.getNode());
6396
6397       // If X has a different width than the result/lhs, sext it or truncate it.
6398       unsigned VTWidth = VT.getSizeInBits();
6399       if (OrigXWidth < VTWidth) {
6400         X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
6401         AddToWorklist(X.getNode());
6402       } else if (OrigXWidth > VTWidth) {
6403         // To get the sign bit in the right place, we have to shift it right
6404         // before truncating.
6405         X = DAG.getNode(ISD::SRL, SDLoc(X),
6406                         X.getValueType(), X,
6407                         DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
6408         AddToWorklist(X.getNode());
6409         X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6410         AddToWorklist(X.getNode());
6411       }
6412
6413       APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6414       X = DAG.getNode(ISD::AND, SDLoc(X), VT,
6415                       X, DAG.getConstant(SignBit, VT));
6416       AddToWorklist(X.getNode());
6417
6418       SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6419                                 VT, N0.getOperand(0));
6420       Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
6421                         Cst, DAG.getConstant(~SignBit, VT));
6422       AddToWorklist(Cst.getNode());
6423
6424       return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
6425     }
6426   }
6427
6428   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
6429   if (N0.getOpcode() == ISD::BUILD_PAIR) {
6430     SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
6431     if (CombineLD.getNode())
6432       return CombineLD;
6433   }
6434
6435   return SDValue();
6436 }
6437
6438 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
6439   EVT VT = N->getValueType(0);
6440   return CombineConsecutiveLoads(N, VT);
6441 }
6442
6443 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
6444 /// operands. DstEltVT indicates the destination element value type.
6445 SDValue DAGCombiner::
6446 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
6447   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
6448
6449   // If this is already the right type, we're done.
6450   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
6451
6452   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
6453   unsigned DstBitSize = DstEltVT.getSizeInBits();
6454
6455   // If this is a conversion of N elements of one type to N elements of another
6456   // type, convert each element.  This handles FP<->INT cases.
6457   if (SrcBitSize == DstBitSize) {
6458     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6459                               BV->getValueType(0).getVectorNumElements());
6460
6461     // Due to the FP element handling below calling this routine recursively,
6462     // we can end up with a scalar-to-vector node here.
6463     if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
6464       return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6465                          DAG.getNode(ISD::BITCAST, SDLoc(BV),
6466                                      DstEltVT, BV->getOperand(0)));
6467
6468     SmallVector<SDValue, 8> Ops;
6469     for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6470       SDValue Op = BV->getOperand(i);
6471       // If the vector element type is not legal, the BUILD_VECTOR operands
6472       // are promoted and implicitly truncated.  Make that explicit here.
6473       if (Op.getValueType() != SrcEltVT)
6474         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
6475       Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
6476                                 DstEltVT, Op));
6477       AddToWorklist(Ops.back().getNode());
6478     }
6479     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6480   }
6481
6482   // Otherwise, we're growing or shrinking the elements.  To avoid having to
6483   // handle annoying details of growing/shrinking FP values, we convert them to
6484   // int first.
6485   if (SrcEltVT.isFloatingPoint()) {
6486     // Convert the input float vector to a int vector where the elements are the
6487     // same sizes.
6488     assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
6489     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
6490     BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
6491     SrcEltVT = IntVT;
6492   }
6493
6494   // Now we know the input is an integer vector.  If the output is a FP type,
6495   // convert to integer first, then to FP of the right size.
6496   if (DstEltVT.isFloatingPoint()) {
6497     assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
6498     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
6499     SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
6500
6501     // Next, convert to FP elements of the same size.
6502     return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
6503   }
6504
6505   // Okay, we know the src/dst types are both integers of differing types.
6506   // Handling growing first.
6507   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
6508   if (SrcBitSize < DstBitSize) {
6509     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
6510
6511     SmallVector<SDValue, 8> Ops;
6512     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
6513          i += NumInputsPerOutput) {
6514       bool isLE = TLI.isLittleEndian();
6515       APInt NewBits = APInt(DstBitSize, 0);
6516       bool EltIsUndef = true;
6517       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
6518         // Shift the previously computed bits over.
6519         NewBits <<= SrcBitSize;
6520         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
6521         if (Op.getOpcode() == ISD::UNDEF) continue;
6522         EltIsUndef = false;
6523
6524         NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
6525                    zextOrTrunc(SrcBitSize).zext(DstBitSize);
6526       }
6527
6528       if (EltIsUndef)
6529         Ops.push_back(DAG.getUNDEF(DstEltVT));
6530       else
6531         Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
6532     }
6533
6534     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
6535     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6536   }
6537
6538   // Finally, this must be the case where we are shrinking elements: each input
6539   // turns into multiple outputs.
6540   bool isS2V = ISD::isScalarToVector(BV);
6541   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
6542   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6543                             NumOutputsPerInput*BV->getNumOperands());
6544   SmallVector<SDValue, 8> Ops;
6545
6546   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6547     if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
6548       for (unsigned j = 0; j != NumOutputsPerInput; ++j)
6549         Ops.push_back(DAG.getUNDEF(DstEltVT));
6550       continue;
6551     }
6552
6553     APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
6554                   getAPIntValue().zextOrTrunc(SrcBitSize);
6555
6556     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
6557       APInt ThisVal = OpVal.trunc(DstBitSize);
6558       Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
6559       if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
6560         // Simply turn this into a SCALAR_TO_VECTOR of the new type.
6561         return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6562                            Ops[0]);
6563       OpVal = OpVal.lshr(DstBitSize);
6564     }
6565
6566     // For big endian targets, swap the order of the pieces of each element.
6567     if (TLI.isBigEndian())
6568       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
6569   }
6570
6571   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6572 }
6573
6574 SDValue DAGCombiner::visitFADD(SDNode *N) {
6575   SDValue N0 = N->getOperand(0);
6576   SDValue N1 = N->getOperand(1);
6577   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6578   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6579   EVT VT = N->getValueType(0);
6580   const TargetOptions &Options = DAG.getTarget().Options;
6581
6582   // fold vector ops
6583   if (VT.isVector()) {
6584     SDValue FoldedVOp = SimplifyVBinOp(N);
6585     if (FoldedVOp.getNode()) return FoldedVOp;
6586   }
6587
6588   // fold (fadd c1, c2) -> c1 + c2
6589   if (N0CFP && N1CFP)
6590     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
6591
6592   // canonicalize constant to RHS
6593   if (N0CFP && !N1CFP)
6594     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
6595
6596   // fold (fadd A, (fneg B)) -> (fsub A, B)
6597   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6598       isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
6599     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
6600                        GetNegatedExpression(N1, DAG, LegalOperations));
6601
6602   // fold (fadd (fneg A), B) -> (fsub B, A)
6603   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6604       isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
6605     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
6606                        GetNegatedExpression(N0, DAG, LegalOperations));
6607
6608   // If 'unsafe math' is enabled, fold lots of things.
6609   if (Options.UnsafeFPMath) {
6610     // No FP constant should be created after legalization as Instruction
6611     // Selection pass has a hard time dealing with FP constants.
6612     bool AllowNewConst = (Level < AfterLegalizeDAG);
6613
6614     // fold (fadd A, 0) -> A
6615     if (N1CFP && N1CFP->getValueAPF().isZero())
6616       return N0;
6617
6618     // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
6619     if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
6620         isa<ConstantFPSDNode>(N0.getOperand(1)))
6621       return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
6622                          DAG.getNode(ISD::FADD, SDLoc(N), VT,
6623                                      N0.getOperand(1), N1));
6624
6625     // If allowed, fold (fadd (fneg x), x) -> 0.0
6626     if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
6627       return DAG.getConstantFP(0.0, VT);
6628
6629     // If allowed, fold (fadd x, (fneg x)) -> 0.0
6630     if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
6631       return DAG.getConstantFP(0.0, VT);
6632
6633     // We can fold chains of FADD's of the same value into multiplications.
6634     // This transform is not safe in general because we are reducing the number
6635     // of rounding steps.
6636     if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
6637       if (N0.getOpcode() == ISD::FMUL) {
6638         ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6639         ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6640
6641         // (fadd (fmul x, c), x) -> (fmul x, c+1)
6642         if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
6643           SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6644                                        SDValue(CFP01, 0),
6645                                        DAG.getConstantFP(1.0, VT));
6646           return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, NewCFP);
6647         }
6648
6649         // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
6650         if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
6651             N1.getOperand(0) == N1.getOperand(1) &&
6652             N0.getOperand(0) == N1.getOperand(0)) {
6653           SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6654                                        SDValue(CFP01, 0),
6655                                        DAG.getConstantFP(2.0, VT));
6656           return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6657                              N0.getOperand(0), NewCFP);
6658         }
6659       }
6660
6661       if (N1.getOpcode() == ISD::FMUL) {
6662         ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6663         ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
6664
6665         // (fadd x, (fmul x, c)) -> (fmul x, c+1)
6666         if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
6667           SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6668                                        SDValue(CFP11, 0),
6669                                        DAG.getConstantFP(1.0, VT));
6670           return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, NewCFP);
6671         }
6672
6673         // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
6674         if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
6675             N0.getOperand(0) == N0.getOperand(1) &&
6676             N1.getOperand(0) == N0.getOperand(0)) {
6677           SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6678                                        SDValue(CFP11, 0),
6679                                        DAG.getConstantFP(2.0, VT));
6680           return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1.getOperand(0), NewCFP);
6681         }
6682       }
6683
6684       if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
6685         ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6686         // (fadd (fadd x, x), x) -> (fmul x, 3.0)
6687         if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
6688             (N0.getOperand(0) == N1))
6689           return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6690                              N1, DAG.getConstantFP(3.0, VT));
6691       }
6692
6693       if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
6694         ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6695         // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
6696         if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
6697             N1.getOperand(0) == N0)
6698           return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6699                              N0, DAG.getConstantFP(3.0, VT));
6700       }
6701
6702       // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
6703       if (AllowNewConst &&
6704           N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
6705           N0.getOperand(0) == N0.getOperand(1) &&
6706           N1.getOperand(0) == N1.getOperand(1) &&
6707           N0.getOperand(0) == N1.getOperand(0))
6708         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6709                            N0.getOperand(0), DAG.getConstantFP(4.0, VT));
6710     }
6711   } // enable-unsafe-fp-math
6712
6713   // FADD -> FMA combines:
6714   if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) &&
6715       TLI.isFMAFasterThanFMulAndFAdd(VT) &&
6716       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6717
6718     // fold (fadd (fmul x, y), z) -> (fma x, y, z)
6719     if (N0.getOpcode() == ISD::FMUL &&
6720         (N0->hasOneUse() || TLI.enableAggressiveFMAFusion(VT)))
6721       return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6722                          N0.getOperand(0), N0.getOperand(1), N1);
6723
6724     // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
6725     // Note: Commutes FADD operands.
6726     if (N1.getOpcode() == ISD::FMUL &&
6727         (N1->hasOneUse() || TLI.enableAggressiveFMAFusion(VT)))
6728       return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6729                          N1.getOperand(0), N1.getOperand(1), N0);
6730   }
6731
6732   return SDValue();
6733 }
6734
6735 SDValue DAGCombiner::visitFSUB(SDNode *N) {
6736   SDValue N0 = N->getOperand(0);
6737   SDValue N1 = N->getOperand(1);
6738   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
6739   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
6740   EVT VT = N->getValueType(0);
6741   SDLoc dl(N);
6742   const TargetOptions &Options = DAG.getTarget().Options;
6743
6744   // fold vector ops
6745   if (VT.isVector()) {
6746     SDValue FoldedVOp = SimplifyVBinOp(N);
6747     if (FoldedVOp.getNode()) return FoldedVOp;
6748   }
6749
6750   // fold (fsub c1, c2) -> c1-c2
6751   if (N0CFP && N1CFP)
6752     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
6753
6754   // fold (fsub A, (fneg B)) -> (fadd A, B)
6755   if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
6756     return DAG.getNode(ISD::FADD, dl, VT, N0,
6757                        GetNegatedExpression(N1, DAG, LegalOperations));
6758
6759   // If 'unsafe math' is enabled, fold lots of things.
6760   if (Options.UnsafeFPMath) {
6761     // (fsub A, 0) -> A
6762     if (N1CFP && N1CFP->getValueAPF().isZero())
6763       return N0;
6764
6765     // (fsub 0, B) -> -B
6766     if (N0CFP && N0CFP->getValueAPF().isZero()) {
6767       if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
6768         return GetNegatedExpression(N1, DAG, LegalOperations);
6769       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6770         return DAG.getNode(ISD::FNEG, dl, VT, N1);
6771     }
6772
6773     // (fsub x, x) -> 0.0
6774     if (N0 == N1)
6775       return DAG.getConstantFP(0.0f, VT);
6776
6777     // (fsub x, (fadd x, y)) -> (fneg y)
6778     // (fsub x, (fadd y, x)) -> (fneg y)
6779     if (N1.getOpcode() == ISD::FADD) {
6780       SDValue N10 = N1->getOperand(0);
6781       SDValue N11 = N1->getOperand(1);
6782
6783       if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
6784         return GetNegatedExpression(N11, DAG, LegalOperations);
6785
6786       if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
6787         return GetNegatedExpression(N10, DAG, LegalOperations);
6788     }
6789   }
6790
6791   // FSUB -> FMA combines:
6792   if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) &&
6793       TLI.isFMAFasterThanFMulAndFAdd(VT) &&
6794       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6795
6796     // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
6797     if (N0.getOpcode() == ISD::FMUL &&
6798         (N0->hasOneUse() || TLI.enableAggressiveFMAFusion(VT)))
6799       return DAG.getNode(ISD::FMA, dl, VT,
6800                          N0.getOperand(0), N0.getOperand(1),
6801                          DAG.getNode(ISD::FNEG, dl, VT, N1));
6802
6803     // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
6804     // Note: Commutes FSUB operands.
6805     if (N1.getOpcode() == ISD::FMUL &&
6806         (N1->hasOneUse() || TLI.enableAggressiveFMAFusion(VT)))
6807       return DAG.getNode(ISD::FMA, dl, VT,
6808                          DAG.getNode(ISD::FNEG, dl, VT,
6809                          N1.getOperand(0)),
6810                          N1.getOperand(1), N0);
6811
6812     // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
6813     if (N0.getOpcode() == ISD::FNEG &&
6814         N0.getOperand(0).getOpcode() == ISD::FMUL &&
6815         ((N0->hasOneUse() && N0.getOperand(0).hasOneUse()) ||
6816             TLI.enableAggressiveFMAFusion(VT))) {
6817       SDValue N00 = N0.getOperand(0).getOperand(0);
6818       SDValue N01 = N0.getOperand(0).getOperand(1);
6819       return DAG.getNode(ISD::FMA, dl, VT,
6820                          DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
6821                          DAG.getNode(ISD::FNEG, dl, VT, N1));
6822     }
6823   }
6824
6825   return SDValue();
6826 }
6827
6828 SDValue DAGCombiner::visitFMUL(SDNode *N) {
6829   SDValue N0 = N->getOperand(0);
6830   SDValue N1 = N->getOperand(1);
6831   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
6832   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
6833   EVT VT = N->getValueType(0);
6834   const TargetOptions &Options = DAG.getTarget().Options;
6835
6836   // fold vector ops
6837   if (VT.isVector()) {
6838     // This just handles C1 * C2 for vectors. Other vector folds are below.
6839     SDValue FoldedVOp = SimplifyVBinOp(N);
6840     if (FoldedVOp.getNode())
6841       return FoldedVOp;
6842     // Canonicalize vector constant to RHS.
6843     if (N0.getOpcode() == ISD::BUILD_VECTOR &&
6844         N1.getOpcode() != ISD::BUILD_VECTOR)
6845       if (auto *BV0 = dyn_cast<BuildVectorSDNode>(N0))
6846         if (BV0->isConstant())
6847           return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0);
6848   }
6849
6850   // fold (fmul c1, c2) -> c1*c2
6851   if (N0CFP && N1CFP)
6852     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
6853
6854   // canonicalize constant to RHS
6855   if (N0CFP && !N1CFP)
6856     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
6857
6858   // fold (fmul A, 1.0) -> A
6859   if (N1CFP && N1CFP->isExactlyValue(1.0))
6860     return N0;
6861
6862   if (Options.UnsafeFPMath) {
6863     // fold (fmul A, 0) -> 0
6864     if (N1CFP && N1CFP->getValueAPF().isZero())
6865       return N1;
6866
6867     // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
6868     if (N0.getOpcode() == ISD::FMUL) {
6869       // Fold scalars or any vector constants (not just splats).
6870       // This fold is done in general by InstCombine, but extra fmul insts
6871       // may have been generated during lowering.
6872       SDValue N01 = N0.getOperand(1);
6873       auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
6874       auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
6875       if ((N1CFP && isConstOrConstSplatFP(N01)) ||
6876           (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
6877         SDLoc SL(N);
6878         SDValue MulConsts = DAG.getNode(ISD::FMUL, SL, VT, N01, N1);
6879         return DAG.getNode(ISD::FMUL, SL, VT, N0.getOperand(0), MulConsts);
6880       }
6881     }
6882
6883     // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
6884     // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
6885     // during an early run of DAGCombiner can prevent folding with fmuls
6886     // inserted during lowering.
6887     if (N0.getOpcode() == ISD::FADD && N0.getOperand(0) == N0.getOperand(1)) {
6888       SDLoc SL(N);
6889       const SDValue Two = DAG.getConstantFP(2.0, VT);
6890       SDValue MulConsts = DAG.getNode(ISD::FMUL, SL, VT, Two, N1);
6891       return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0), MulConsts);
6892     }
6893   }
6894
6895   // fold (fmul X, 2.0) -> (fadd X, X)
6896   if (N1CFP && N1CFP->isExactlyValue(+2.0))
6897     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
6898
6899   // fold (fmul X, -1.0) -> (fneg X)
6900   if (N1CFP && N1CFP->isExactlyValue(-1.0))
6901     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6902       return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
6903
6904   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
6905   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
6906     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
6907       // Both can be negated for free, check to see if at least one is cheaper
6908       // negated.
6909       if (LHSNeg == 2 || RHSNeg == 2)
6910         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6911                            GetNegatedExpression(N0, DAG, LegalOperations),
6912                            GetNegatedExpression(N1, DAG, LegalOperations));
6913     }
6914   }
6915
6916   return SDValue();
6917 }
6918
6919 SDValue DAGCombiner::visitFMA(SDNode *N) {
6920   SDValue N0 = N->getOperand(0);
6921   SDValue N1 = N->getOperand(1);
6922   SDValue N2 = N->getOperand(2);
6923   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6924   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6925   EVT VT = N->getValueType(0);
6926   SDLoc dl(N);
6927   const TargetOptions &Options = DAG.getTarget().Options;
6928
6929   // Constant fold FMA.
6930   if (isa<ConstantFPSDNode>(N0) &&
6931       isa<ConstantFPSDNode>(N1) &&
6932       isa<ConstantFPSDNode>(N2)) {
6933     return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
6934   }
6935
6936   if (Options.UnsafeFPMath) {
6937     if (N0CFP && N0CFP->isZero())
6938       return N2;
6939     if (N1CFP && N1CFP->isZero())
6940       return N2;
6941   }
6942   if (N0CFP && N0CFP->isExactlyValue(1.0))
6943     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
6944   if (N1CFP && N1CFP->isExactlyValue(1.0))
6945     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
6946
6947   // Canonicalize (fma c, x, y) -> (fma x, c, y)
6948   if (N0CFP && !N1CFP)
6949     return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
6950
6951   // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
6952   if (Options.UnsafeFPMath && N1CFP &&
6953       N2.getOpcode() == ISD::FMUL &&
6954       N0 == N2.getOperand(0) &&
6955       N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
6956     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6957                        DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
6958   }
6959
6960
6961   // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
6962   if (Options.UnsafeFPMath &&
6963       N0.getOpcode() == ISD::FMUL && N1CFP &&
6964       N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
6965     return DAG.getNode(ISD::FMA, dl, VT,
6966                        N0.getOperand(0),
6967                        DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
6968                        N2);
6969   }
6970
6971   // (fma x, 1, y) -> (fadd x, y)
6972   // (fma x, -1, y) -> (fadd (fneg x), y)
6973   if (N1CFP) {
6974     if (N1CFP->isExactlyValue(1.0))
6975       return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
6976
6977     if (N1CFP->isExactlyValue(-1.0) &&
6978         (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
6979       SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
6980       AddToWorklist(RHSNeg.getNode());
6981       return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
6982     }
6983   }
6984
6985   // (fma x, c, x) -> (fmul x, (c+1))
6986   if (Options.UnsafeFPMath && N1CFP && N0 == N2)
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   // (fma x, c, (fneg x)) -> (fmul x, (c-1))
6992   if (Options.UnsafeFPMath && N1CFP &&
6993       N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
6994     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6995                        DAG.getNode(ISD::FADD, dl, VT,
6996                                    N1, DAG.getConstantFP(-1.0, VT)));
6997
6998
6999   return SDValue();
7000 }
7001
7002 SDValue DAGCombiner::visitFDIV(SDNode *N) {
7003   SDValue N0 = N->getOperand(0);
7004   SDValue N1 = N->getOperand(1);
7005   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7006   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7007   EVT VT = N->getValueType(0);
7008   SDLoc DL(N);
7009   const TargetOptions &Options = DAG.getTarget().Options;
7010
7011   // fold vector ops
7012   if (VT.isVector()) {
7013     SDValue FoldedVOp = SimplifyVBinOp(N);
7014     if (FoldedVOp.getNode()) return FoldedVOp;
7015   }
7016
7017   // fold (fdiv c1, c2) -> c1/c2
7018   if (N0CFP && N1CFP)
7019     return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
7020
7021   if (Options.UnsafeFPMath) {
7022     // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
7023     if (N1CFP) {
7024       // Compute the reciprocal 1.0 / c2.
7025       APFloat N1APF = N1CFP->getValueAPF();
7026       APFloat Recip(N1APF.getSemantics(), 1); // 1.0
7027       APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
7028       // Only do the transform if the reciprocal is a legal fp immediate that
7029       // isn't too nasty (eg NaN, denormal, ...).
7030       if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
7031           (!LegalOperations ||
7032            // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
7033            // backend)... we should handle this gracefully after Legalize.
7034            // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
7035            TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
7036            TLI.isFPImmLegal(Recip, VT)))
7037         return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
7038                            DAG.getConstantFP(Recip, VT));
7039     }
7040
7041     // If this FDIV is part of a reciprocal square root, it may be folded
7042     // into a target-specific square root estimate instruction.
7043     if (N1.getOpcode() == ISD::FSQRT) {
7044       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0))) {
7045         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7046       }
7047     } else if (N1.getOpcode() == ISD::FP_EXTEND &&
7048                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
7049       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
7050         RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
7051         AddToWorklist(RV.getNode());
7052         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7053       }
7054     } else if (N1.getOpcode() == ISD::FP_ROUND &&
7055                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
7056       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
7057         RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
7058         AddToWorklist(RV.getNode());
7059         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7060       }
7061     } else if (N1.getOpcode() == ISD::FMUL) {
7062       // Look through an FMUL. Even though this won't remove the FDIV directly,
7063       // it's still worthwhile to get rid of the FSQRT if possible.
7064       SDValue SqrtOp;
7065       SDValue OtherOp;
7066       if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
7067         SqrtOp = N1.getOperand(0);
7068         OtherOp = N1.getOperand(1);
7069       } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
7070         SqrtOp = N1.getOperand(1);
7071         OtherOp = N1.getOperand(0);
7072       }
7073       if (SqrtOp.getNode()) {
7074         // We found a FSQRT, so try to make this fold:
7075         // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
7076         if (SDValue RV = BuildRsqrtEstimate(SqrtOp.getOperand(0))) {
7077           RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp);
7078           AddToWorklist(RV.getNode());
7079           return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7080         }
7081       }
7082     }
7083
7084     // Fold into a reciprocal estimate and multiply instead of a real divide.
7085     if (SDValue RV = BuildReciprocalEstimate(N1)) {
7086       AddToWorklist(RV.getNode());
7087       return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7088     }
7089   }
7090
7091   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
7092   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
7093     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
7094       // Both can be negated for free, check to see if at least one is cheaper
7095       // negated.
7096       if (LHSNeg == 2 || RHSNeg == 2)
7097         return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
7098                            GetNegatedExpression(N0, DAG, LegalOperations),
7099                            GetNegatedExpression(N1, DAG, LegalOperations));
7100     }
7101   }
7102
7103   return SDValue();
7104 }
7105
7106 SDValue DAGCombiner::visitFREM(SDNode *N) {
7107   SDValue N0 = N->getOperand(0);
7108   SDValue N1 = N->getOperand(1);
7109   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7110   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7111   EVT VT = N->getValueType(0);
7112
7113   // fold (frem c1, c2) -> fmod(c1,c2)
7114   if (N0CFP && N1CFP)
7115     return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
7116
7117   return SDValue();
7118 }
7119
7120 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
7121   if (DAG.getTarget().Options.UnsafeFPMath) {
7122     // Compute this as X * (1/sqrt(X)) = X * (X ** -0.5)
7123     if (SDValue RV = BuildRsqrtEstimate(N->getOperand(0))) {
7124       EVT VT = RV.getValueType();
7125       RV = DAG.getNode(ISD::FMUL, SDLoc(N), VT, N->getOperand(0), RV);
7126       AddToWorklist(RV.getNode());
7127
7128       // Unfortunately, RV is now NaN if the input was exactly 0.
7129       // Select out this case and force the answer to 0.
7130       SDValue Zero = DAG.getConstantFP(0.0, VT);
7131       SDValue ZeroCmp =
7132         DAG.getSetCC(SDLoc(N), TLI.getSetCCResultType(*DAG.getContext(), VT),
7133                      N->getOperand(0), Zero, ISD::SETEQ);
7134       AddToWorklist(ZeroCmp.getNode());
7135       AddToWorklist(RV.getNode());
7136
7137       RV = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT,
7138                        SDLoc(N), VT, ZeroCmp, Zero, RV);
7139       return RV;
7140     }
7141   }
7142   return SDValue();
7143 }
7144
7145 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
7146   SDValue N0 = N->getOperand(0);
7147   SDValue N1 = N->getOperand(1);
7148   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7149   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7150   EVT VT = N->getValueType(0);
7151
7152   if (N0CFP && N1CFP)  // Constant fold
7153     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
7154
7155   if (N1CFP) {
7156     const APFloat& V = N1CFP->getValueAPF();
7157     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
7158     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
7159     if (!V.isNegative()) {
7160       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
7161         return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7162     } else {
7163       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
7164         return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7165                            DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
7166     }
7167   }
7168
7169   // copysign(fabs(x), y) -> copysign(x, y)
7170   // copysign(fneg(x), y) -> copysign(x, y)
7171   // copysign(copysign(x,z), y) -> copysign(x, y)
7172   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
7173       N0.getOpcode() == ISD::FCOPYSIGN)
7174     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7175                        N0.getOperand(0), N1);
7176
7177   // copysign(x, abs(y)) -> abs(x)
7178   if (N1.getOpcode() == ISD::FABS)
7179     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7180
7181   // copysign(x, copysign(y,z)) -> copysign(x, z)
7182   if (N1.getOpcode() == ISD::FCOPYSIGN)
7183     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7184                        N0, N1.getOperand(1));
7185
7186   // copysign(x, fp_extend(y)) -> copysign(x, y)
7187   // copysign(x, fp_round(y)) -> copysign(x, y)
7188   if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
7189     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7190                        N0, N1.getOperand(0));
7191
7192   return SDValue();
7193 }
7194
7195 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
7196   SDValue N0 = N->getOperand(0);
7197   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
7198   EVT VT = N->getValueType(0);
7199   EVT OpVT = N0.getValueType();
7200
7201   // fold (sint_to_fp c1) -> c1fp
7202   if (N0C &&
7203       // ...but only if the target supports immediate floating-point values
7204       (!LegalOperations ||
7205        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7206     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7207
7208   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
7209   // but UINT_TO_FP is legal on this target, try to convert.
7210   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
7211       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
7212     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
7213     if (DAG.SignBitIsZero(N0))
7214       return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7215   }
7216
7217   // The next optimizations are desirable only if SELECT_CC can be lowered.
7218   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
7219     // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7220     if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
7221         !VT.isVector() &&
7222         (!LegalOperations ||
7223          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7224       SDValue Ops[] =
7225         { N0.getOperand(0), N0.getOperand(1),
7226           DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
7227           N0.getOperand(2) };
7228       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7229     }
7230
7231     // fold (sint_to_fp (zext (setcc x, y, cc))) ->
7232     //      (select_cc x, y, 1.0, 0.0,, cc)
7233     if (N0.getOpcode() == ISD::ZERO_EXTEND &&
7234         N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
7235         (!LegalOperations ||
7236          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7237       SDValue Ops[] =
7238         { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
7239           DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
7240           N0.getOperand(0).getOperand(2) };
7241       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7242     }
7243   }
7244
7245   return SDValue();
7246 }
7247
7248 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
7249   SDValue N0 = N->getOperand(0);
7250   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
7251   EVT VT = N->getValueType(0);
7252   EVT OpVT = N0.getValueType();
7253
7254   // fold (uint_to_fp c1) -> c1fp
7255   if (N0C &&
7256       // ...but only if the target supports immediate floating-point values
7257       (!LegalOperations ||
7258        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7259     return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7260
7261   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
7262   // but SINT_TO_FP is legal on this target, try to convert.
7263   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
7264       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
7265     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
7266     if (DAG.SignBitIsZero(N0))
7267       return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7268   }
7269
7270   // The next optimizations are desirable only if SELECT_CC can be lowered.
7271   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
7272     // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7273
7274     if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
7275         (!LegalOperations ||
7276          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7277       SDValue Ops[] =
7278         { N0.getOperand(0), N0.getOperand(1),
7279           DAG.getConstantFP(1.0, VT),  DAG.getConstantFP(0.0, VT),
7280           N0.getOperand(2) };
7281       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7282     }
7283   }
7284
7285   return SDValue();
7286 }
7287
7288 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
7289   SDValue N0 = N->getOperand(0);
7290   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7291   EVT VT = N->getValueType(0);
7292
7293   // fold (fp_to_sint c1fp) -> c1
7294   if (N0CFP)
7295     return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
7296
7297   return SDValue();
7298 }
7299
7300 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
7301   SDValue N0 = N->getOperand(0);
7302   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7303   EVT VT = N->getValueType(0);
7304
7305   // fold (fp_to_uint c1fp) -> c1
7306   if (N0CFP)
7307     return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
7308
7309   return SDValue();
7310 }
7311
7312 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
7313   SDValue N0 = N->getOperand(0);
7314   SDValue N1 = N->getOperand(1);
7315   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7316   EVT VT = N->getValueType(0);
7317
7318   // fold (fp_round c1fp) -> c1fp
7319   if (N0CFP)
7320     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
7321
7322   // fold (fp_round (fp_extend x)) -> x
7323   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
7324     return N0.getOperand(0);
7325
7326   // fold (fp_round (fp_round x)) -> (fp_round x)
7327   if (N0.getOpcode() == ISD::FP_ROUND) {
7328     // This is a value preserving truncation if both round's are.
7329     bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
7330                    N0.getNode()->getConstantOperandVal(1) == 1;
7331     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
7332                        DAG.getIntPtrConstant(IsTrunc));
7333   }
7334
7335   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
7336   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
7337     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
7338                               N0.getOperand(0), N1);
7339     AddToWorklist(Tmp.getNode());
7340     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7341                        Tmp, N0.getOperand(1));
7342   }
7343
7344   return SDValue();
7345 }
7346
7347 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
7348   SDValue N0 = N->getOperand(0);
7349   EVT VT = N->getValueType(0);
7350   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
7351   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7352
7353   // fold (fp_round_inreg c1fp) -> c1fp
7354   if (N0CFP && isTypeLegal(EVT)) {
7355     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
7356     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
7357   }
7358
7359   return SDValue();
7360 }
7361
7362 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
7363   SDValue N0 = N->getOperand(0);
7364   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7365   EVT VT = N->getValueType(0);
7366
7367   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
7368   if (N->hasOneUse() &&
7369       N->use_begin()->getOpcode() == ISD::FP_ROUND)
7370     return SDValue();
7371
7372   // fold (fp_extend c1fp) -> c1fp
7373   if (N0CFP)
7374     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
7375
7376   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
7377   // value of X.
7378   if (N0.getOpcode() == ISD::FP_ROUND
7379       && N0.getNode()->getConstantOperandVal(1) == 1) {
7380     SDValue In = N0.getOperand(0);
7381     if (In.getValueType() == VT) return In;
7382     if (VT.bitsLT(In.getValueType()))
7383       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
7384                          In, N0.getOperand(1));
7385     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
7386   }
7387
7388   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
7389   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7390        TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType())) {
7391     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7392     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
7393                                      LN0->getChain(),
7394                                      LN0->getBasePtr(), N0.getValueType(),
7395                                      LN0->getMemOperand());
7396     CombineTo(N, ExtLoad);
7397     CombineTo(N0.getNode(),
7398               DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
7399                           N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
7400               ExtLoad.getValue(1));
7401     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7402   }
7403
7404   return SDValue();
7405 }
7406
7407 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
7408   SDValue N0 = N->getOperand(0);
7409   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7410   EVT VT = N->getValueType(0);
7411
7412   // fold (fceil c1) -> fceil(c1)
7413   if (N0CFP)
7414     return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
7415
7416   return SDValue();
7417 }
7418
7419 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
7420   SDValue N0 = N->getOperand(0);
7421   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7422   EVT VT = N->getValueType(0);
7423
7424   // fold (ftrunc c1) -> ftrunc(c1)
7425   if (N0CFP)
7426     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
7427
7428   return SDValue();
7429 }
7430
7431 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
7432   SDValue N0 = N->getOperand(0);
7433   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7434   EVT VT = N->getValueType(0);
7435
7436   // fold (ffloor c1) -> ffloor(c1)
7437   if (N0CFP)
7438     return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
7439
7440   return SDValue();
7441 }
7442
7443 // FIXME: FNEG and FABS have a lot in common; refactor.
7444 SDValue DAGCombiner::visitFNEG(SDNode *N) {
7445   SDValue N0 = N->getOperand(0);
7446   EVT VT = N->getValueType(0);
7447
7448   if (VT.isVector()) {
7449     SDValue FoldedVOp = SimplifyVUnaryOp(N);
7450     if (FoldedVOp.getNode()) return FoldedVOp;
7451   }
7452
7453   // Constant fold FNEG.
7454   if (isa<ConstantFPSDNode>(N0))
7455     return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N->getOperand(0));
7456
7457   if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
7458                          &DAG.getTarget().Options))
7459     return GetNegatedExpression(N0, DAG, LegalOperations);
7460
7461   // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
7462   // constant pool values.
7463   if (!TLI.isFNegFree(VT) &&
7464       N0.getOpcode() == ISD::BITCAST &&
7465       N0.getNode()->hasOneUse()) {
7466     SDValue Int = N0.getOperand(0);
7467     EVT IntVT = Int.getValueType();
7468     if (IntVT.isInteger() && !IntVT.isVector()) {
7469       APInt SignMask;
7470       if (N0.getValueType().isVector()) {
7471         // For a vector, get a mask such as 0x80... per scalar element
7472         // and splat it.
7473         SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
7474         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
7475       } else {
7476         // For a scalar, just generate 0x80...
7477         SignMask = APInt::getSignBit(IntVT.getSizeInBits());
7478       }
7479       Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
7480                         DAG.getConstant(SignMask, IntVT));
7481       AddToWorklist(Int.getNode());
7482       return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int);
7483     }
7484   }
7485
7486   // (fneg (fmul c, x)) -> (fmul -c, x)
7487   if (N0.getOpcode() == ISD::FMUL) {
7488     ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
7489     if (CFP1) {
7490       APFloat CVal = CFP1->getValueAPF();
7491       CVal.changeSign();
7492       if (Level >= AfterLegalizeDAG &&
7493           (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
7494            TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
7495         return DAG.getNode(
7496             ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
7497             DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)));
7498     }
7499   }
7500
7501   return SDValue();
7502 }
7503
7504 SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
7505   SDValue N0 = N->getOperand(0);
7506   SDValue N1 = N->getOperand(1);
7507   const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7508   const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7509
7510   if (N0CFP && N1CFP) {
7511     const APFloat &C0 = N0CFP->getValueAPF();
7512     const APFloat &C1 = N1CFP->getValueAPF();
7513     return DAG.getConstantFP(minnum(C0, C1), N->getValueType(0));
7514   }
7515
7516   if (N0CFP) {
7517     EVT VT = N->getValueType(0);
7518     // Canonicalize to constant on RHS.
7519     return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
7520   }
7521
7522   return SDValue();
7523 }
7524
7525 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
7526   SDValue N0 = N->getOperand(0);
7527   SDValue N1 = N->getOperand(1);
7528   const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7529   const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7530
7531   if (N0CFP && N1CFP) {
7532     const APFloat &C0 = N0CFP->getValueAPF();
7533     const APFloat &C1 = N1CFP->getValueAPF();
7534     return DAG.getConstantFP(maxnum(C0, C1), N->getValueType(0));
7535   }
7536
7537   if (N0CFP) {
7538     EVT VT = N->getValueType(0);
7539     // Canonicalize to constant on RHS.
7540     return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
7541   }
7542
7543   return SDValue();
7544 }
7545
7546 SDValue DAGCombiner::visitFABS(SDNode *N) {
7547   SDValue N0 = N->getOperand(0);
7548   EVT VT = N->getValueType(0);
7549
7550   if (VT.isVector()) {
7551     SDValue FoldedVOp = SimplifyVUnaryOp(N);
7552     if (FoldedVOp.getNode()) return FoldedVOp;
7553   }
7554
7555   // fold (fabs c1) -> fabs(c1)
7556   if (isa<ConstantFPSDNode>(N0))
7557     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7558
7559   // fold (fabs (fabs x)) -> (fabs x)
7560   if (N0.getOpcode() == ISD::FABS)
7561     return N->getOperand(0);
7562
7563   // fold (fabs (fneg x)) -> (fabs x)
7564   // fold (fabs (fcopysign x, y)) -> (fabs x)
7565   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
7566     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
7567
7568   // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
7569   // constant pool values.
7570   if (!TLI.isFAbsFree(VT) &&
7571       N0.getOpcode() == ISD::BITCAST &&
7572       N0.getNode()->hasOneUse()) {
7573     SDValue Int = N0.getOperand(0);
7574     EVT IntVT = Int.getValueType();
7575     if (IntVT.isInteger() && !IntVT.isVector()) {
7576       APInt SignMask;
7577       if (N0.getValueType().isVector()) {
7578         // For a vector, get a mask such as 0x7f... per scalar element
7579         // and splat it.
7580         SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
7581         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
7582       } else {
7583         // For a scalar, just generate 0x7f...
7584         SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
7585       }
7586       Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
7587                         DAG.getConstant(SignMask, IntVT));
7588       AddToWorklist(Int.getNode());
7589       return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int);
7590     }
7591   }
7592
7593   return SDValue();
7594 }
7595
7596 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
7597   SDValue Chain = N->getOperand(0);
7598   SDValue N1 = N->getOperand(1);
7599   SDValue N2 = N->getOperand(2);
7600
7601   // If N is a constant we could fold this into a fallthrough or unconditional
7602   // branch. However that doesn't happen very often in normal code, because
7603   // Instcombine/SimplifyCFG should have handled the available opportunities.
7604   // If we did this folding here, it would be necessary to update the
7605   // MachineBasicBlock CFG, which is awkward.
7606
7607   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
7608   // on the target.
7609   if (N1.getOpcode() == ISD::SETCC &&
7610       TLI.isOperationLegalOrCustom(ISD::BR_CC,
7611                                    N1.getOperand(0).getValueType())) {
7612     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7613                        Chain, N1.getOperand(2),
7614                        N1.getOperand(0), N1.getOperand(1), N2);
7615   }
7616
7617   if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
7618       ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
7619        (N1.getOperand(0).hasOneUse() &&
7620         N1.getOperand(0).getOpcode() == ISD::SRL))) {
7621     SDNode *Trunc = nullptr;
7622     if (N1.getOpcode() == ISD::TRUNCATE) {
7623       // Look pass the truncate.
7624       Trunc = N1.getNode();
7625       N1 = N1.getOperand(0);
7626     }
7627
7628     // Match this pattern so that we can generate simpler code:
7629     //
7630     //   %a = ...
7631     //   %b = and i32 %a, 2
7632     //   %c = srl i32 %b, 1
7633     //   brcond i32 %c ...
7634     //
7635     // into
7636     //
7637     //   %a = ...
7638     //   %b = and i32 %a, 2
7639     //   %c = setcc eq %b, 0
7640     //   brcond %c ...
7641     //
7642     // This applies only when the AND constant value has one bit set and the
7643     // SRL constant is equal to the log2 of the AND constant. The back-end is
7644     // smart enough to convert the result into a TEST/JMP sequence.
7645     SDValue Op0 = N1.getOperand(0);
7646     SDValue Op1 = N1.getOperand(1);
7647
7648     if (Op0.getOpcode() == ISD::AND &&
7649         Op1.getOpcode() == ISD::Constant) {
7650       SDValue AndOp1 = Op0.getOperand(1);
7651
7652       if (AndOp1.getOpcode() == ISD::Constant) {
7653         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
7654
7655         if (AndConst.isPowerOf2() &&
7656             cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
7657           SDValue SetCC =
7658             DAG.getSetCC(SDLoc(N),
7659                          getSetCCResultType(Op0.getValueType()),
7660                          Op0, DAG.getConstant(0, Op0.getValueType()),
7661                          ISD::SETNE);
7662
7663           SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
7664                                           MVT::Other, Chain, SetCC, N2);
7665           // Don't add the new BRCond into the worklist or else SimplifySelectCC
7666           // will convert it back to (X & C1) >> C2.
7667           CombineTo(N, NewBRCond, false);
7668           // Truncate is dead.
7669           if (Trunc)
7670             deleteAndRecombine(Trunc);
7671           // Replace the uses of SRL with SETCC
7672           WorklistRemover DeadNodes(*this);
7673           DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7674           deleteAndRecombine(N1.getNode());
7675           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7676         }
7677       }
7678     }
7679
7680     if (Trunc)
7681       // Restore N1 if the above transformation doesn't match.
7682       N1 = N->getOperand(1);
7683   }
7684
7685   // Transform br(xor(x, y)) -> br(x != y)
7686   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
7687   if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
7688     SDNode *TheXor = N1.getNode();
7689     SDValue Op0 = TheXor->getOperand(0);
7690     SDValue Op1 = TheXor->getOperand(1);
7691     if (Op0.getOpcode() == Op1.getOpcode()) {
7692       // Avoid missing important xor optimizations.
7693       SDValue Tmp = visitXOR(TheXor);
7694       if (Tmp.getNode()) {
7695         if (Tmp.getNode() != TheXor) {
7696           DEBUG(dbgs() << "\nReplacing.8 ";
7697                 TheXor->dump(&DAG);
7698                 dbgs() << "\nWith: ";
7699                 Tmp.getNode()->dump(&DAG);
7700                 dbgs() << '\n');
7701           WorklistRemover DeadNodes(*this);
7702           DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
7703           deleteAndRecombine(TheXor);
7704           return DAG.getNode(ISD::BRCOND, SDLoc(N),
7705                              MVT::Other, Chain, Tmp, N2);
7706         }
7707
7708         // visitXOR has changed XOR's operands or replaced the XOR completely,
7709         // bail out.
7710         return SDValue(N, 0);
7711       }
7712     }
7713
7714     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
7715       bool Equal = false;
7716       if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
7717         if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
7718             Op0.getOpcode() == ISD::XOR) {
7719           TheXor = Op0.getNode();
7720           Equal = true;
7721         }
7722
7723       EVT SetCCVT = N1.getValueType();
7724       if (LegalTypes)
7725         SetCCVT = getSetCCResultType(SetCCVT);
7726       SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
7727                                    SetCCVT,
7728                                    Op0, Op1,
7729                                    Equal ? ISD::SETEQ : ISD::SETNE);
7730       // Replace the uses of XOR with SETCC
7731       WorklistRemover DeadNodes(*this);
7732       DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7733       deleteAndRecombine(N1.getNode());
7734       return DAG.getNode(ISD::BRCOND, SDLoc(N),
7735                          MVT::Other, Chain, SetCC, N2);
7736     }
7737   }
7738
7739   return SDValue();
7740 }
7741
7742 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
7743 //
7744 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
7745   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
7746   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
7747
7748   // If N is a constant we could fold this into a fallthrough or unconditional
7749   // branch. However that doesn't happen very often in normal code, because
7750   // Instcombine/SimplifyCFG should have handled the available opportunities.
7751   // If we did this folding here, it would be necessary to update the
7752   // MachineBasicBlock CFG, which is awkward.
7753
7754   // Use SimplifySetCC to simplify SETCC's.
7755   SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
7756                                CondLHS, CondRHS, CC->get(), SDLoc(N),
7757                                false);
7758   if (Simp.getNode()) AddToWorklist(Simp.getNode());
7759
7760   // fold to a simpler setcc
7761   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
7762     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7763                        N->getOperand(0), Simp.getOperand(2),
7764                        Simp.getOperand(0), Simp.getOperand(1),
7765                        N->getOperand(4));
7766
7767   return SDValue();
7768 }
7769
7770 /// Return true if 'Use' is a load or a store that uses N as its base pointer
7771 /// and that N may be folded in the load / store addressing mode.
7772 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
7773                                     SelectionDAG &DAG,
7774                                     const TargetLowering &TLI) {
7775   EVT VT;
7776   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
7777     if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
7778       return false;
7779     VT = Use->getValueType(0);
7780   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
7781     if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
7782       return false;
7783     VT = ST->getValue().getValueType();
7784   } else
7785     return false;
7786
7787   TargetLowering::AddrMode AM;
7788   if (N->getOpcode() == ISD::ADD) {
7789     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7790     if (Offset)
7791       // [reg +/- imm]
7792       AM.BaseOffs = Offset->getSExtValue();
7793     else
7794       // [reg +/- reg]
7795       AM.Scale = 1;
7796   } else if (N->getOpcode() == ISD::SUB) {
7797     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7798     if (Offset)
7799       // [reg +/- imm]
7800       AM.BaseOffs = -Offset->getSExtValue();
7801     else
7802       // [reg +/- reg]
7803       AM.Scale = 1;
7804   } else
7805     return false;
7806
7807   return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
7808 }
7809
7810 /// Try turning a load/store into a pre-indexed load/store when the base
7811 /// pointer is an add or subtract and it has other uses besides the load/store.
7812 /// After the transformation, the new indexed load/store has effectively folded
7813 /// the add/subtract in and all of its other uses are redirected to the
7814 /// new load/store.
7815 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
7816   if (Level < AfterLegalizeDAG)
7817     return false;
7818
7819   bool isLoad = true;
7820   SDValue Ptr;
7821   EVT VT;
7822   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
7823     if (LD->isIndexed())
7824       return false;
7825     VT = LD->getMemoryVT();
7826     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
7827         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
7828       return false;
7829     Ptr = LD->getBasePtr();
7830   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
7831     if (ST->isIndexed())
7832       return false;
7833     VT = ST->getMemoryVT();
7834     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
7835         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
7836       return false;
7837     Ptr = ST->getBasePtr();
7838     isLoad = false;
7839   } else {
7840     return false;
7841   }
7842
7843   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
7844   // out.  There is no reason to make this a preinc/predec.
7845   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
7846       Ptr.getNode()->hasOneUse())
7847     return false;
7848
7849   // Ask the target to do addressing mode selection.
7850   SDValue BasePtr;
7851   SDValue Offset;
7852   ISD::MemIndexedMode AM = ISD::UNINDEXED;
7853   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
7854     return false;
7855
7856   // Backends without true r+i pre-indexed forms may need to pass a
7857   // constant base with a variable offset so that constant coercion
7858   // will work with the patterns in canonical form.
7859   bool Swapped = false;
7860   if (isa<ConstantSDNode>(BasePtr)) {
7861     std::swap(BasePtr, Offset);
7862     Swapped = true;
7863   }
7864
7865   // Don't create a indexed load / store with zero offset.
7866   if (isa<ConstantSDNode>(Offset) &&
7867       cast<ConstantSDNode>(Offset)->isNullValue())
7868     return false;
7869
7870   // Try turning it into a pre-indexed load / store except when:
7871   // 1) The new base ptr is a frame index.
7872   // 2) If N is a store and the new base ptr is either the same as or is a
7873   //    predecessor of the value being stored.
7874   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
7875   //    that would create a cycle.
7876   // 4) All uses are load / store ops that use it as old base ptr.
7877
7878   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
7879   // (plus the implicit offset) to a register to preinc anyway.
7880   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7881     return false;
7882
7883   // Check #2.
7884   if (!isLoad) {
7885     SDValue Val = cast<StoreSDNode>(N)->getValue();
7886     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
7887       return false;
7888   }
7889
7890   // If the offset is a constant, there may be other adds of constants that
7891   // can be folded with this one. We should do this to avoid having to keep
7892   // a copy of the original base pointer.
7893   SmallVector<SDNode *, 16> OtherUses;
7894   if (isa<ConstantSDNode>(Offset))
7895     for (SDNode *Use : BasePtr.getNode()->uses()) {
7896       if (Use == Ptr.getNode())
7897         continue;
7898
7899       if (Use->isPredecessorOf(N))
7900         continue;
7901
7902       if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
7903         OtherUses.clear();
7904         break;
7905       }
7906
7907       SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
7908       if (Op1.getNode() == BasePtr.getNode())
7909         std::swap(Op0, Op1);
7910       assert(Op0.getNode() == BasePtr.getNode() &&
7911              "Use of ADD/SUB but not an operand");
7912
7913       if (!isa<ConstantSDNode>(Op1)) {
7914         OtherUses.clear();
7915         break;
7916       }
7917
7918       // FIXME: In some cases, we can be smarter about this.
7919       if (Op1.getValueType() != Offset.getValueType()) {
7920         OtherUses.clear();
7921         break;
7922       }
7923
7924       OtherUses.push_back(Use);
7925     }
7926
7927   if (Swapped)
7928     std::swap(BasePtr, Offset);
7929
7930   // Now check for #3 and #4.
7931   bool RealUse = false;
7932
7933   // Caches for hasPredecessorHelper
7934   SmallPtrSet<const SDNode *, 32> Visited;
7935   SmallVector<const SDNode *, 16> Worklist;
7936
7937   for (SDNode *Use : Ptr.getNode()->uses()) {
7938     if (Use == N)
7939       continue;
7940     if (N->hasPredecessorHelper(Use, Visited, Worklist))
7941       return false;
7942
7943     // If Ptr may be folded in addressing mode of other use, then it's
7944     // not profitable to do this transformation.
7945     if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
7946       RealUse = true;
7947   }
7948
7949   if (!RealUse)
7950     return false;
7951
7952   SDValue Result;
7953   if (isLoad)
7954     Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7955                                 BasePtr, Offset, AM);
7956   else
7957     Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7958                                  BasePtr, Offset, AM);
7959   ++PreIndexedNodes;
7960   ++NodesCombined;
7961   DEBUG(dbgs() << "\nReplacing.4 ";
7962         N->dump(&DAG);
7963         dbgs() << "\nWith: ";
7964         Result.getNode()->dump(&DAG);
7965         dbgs() << '\n');
7966   WorklistRemover DeadNodes(*this);
7967   if (isLoad) {
7968     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7969     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7970   } else {
7971     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7972   }
7973
7974   // Finally, since the node is now dead, remove it from the graph.
7975   deleteAndRecombine(N);
7976
7977   if (Swapped)
7978     std::swap(BasePtr, Offset);
7979
7980   // Replace other uses of BasePtr that can be updated to use Ptr
7981   for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
7982     unsigned OffsetIdx = 1;
7983     if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
7984       OffsetIdx = 0;
7985     assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
7986            BasePtr.getNode() && "Expected BasePtr operand");
7987
7988     // We need to replace ptr0 in the following expression:
7989     //   x0 * offset0 + y0 * ptr0 = t0
7990     // knowing that
7991     //   x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
7992     //
7993     // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
7994     // indexed load/store and the expresion that needs to be re-written.
7995     //
7996     // Therefore, we have:
7997     //   t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
7998
7999     ConstantSDNode *CN =
8000       cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
8001     int X0, X1, Y0, Y1;
8002     APInt Offset0 = CN->getAPIntValue();
8003     APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
8004
8005     X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
8006     Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
8007     X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
8008     Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
8009
8010     unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
8011
8012     APInt CNV = Offset0;
8013     if (X0 < 0) CNV = -CNV;
8014     if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
8015     else CNV = CNV - Offset1;
8016
8017     // We can now generate the new expression.
8018     SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
8019     SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
8020
8021     SDValue NewUse = DAG.getNode(Opcode,
8022                                  SDLoc(OtherUses[i]),
8023                                  OtherUses[i]->getValueType(0), NewOp1, NewOp2);
8024     DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
8025     deleteAndRecombine(OtherUses[i]);
8026   }
8027
8028   // Replace the uses of Ptr with uses of the updated base value.
8029   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
8030   deleteAndRecombine(Ptr.getNode());
8031
8032   return true;
8033 }
8034
8035 /// Try to combine a load/store with a add/sub of the base pointer node into a
8036 /// post-indexed load/store. The transformation folded the add/subtract into the
8037 /// new indexed load/store effectively and all of its uses are redirected to the
8038 /// new load/store.
8039 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
8040   if (Level < AfterLegalizeDAG)
8041     return false;
8042
8043   bool isLoad = true;
8044   SDValue Ptr;
8045   EVT VT;
8046   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
8047     if (LD->isIndexed())
8048       return false;
8049     VT = LD->getMemoryVT();
8050     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
8051         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
8052       return false;
8053     Ptr = LD->getBasePtr();
8054   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
8055     if (ST->isIndexed())
8056       return false;
8057     VT = ST->getMemoryVT();
8058     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
8059         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
8060       return false;
8061     Ptr = ST->getBasePtr();
8062     isLoad = false;
8063   } else {
8064     return false;
8065   }
8066
8067   if (Ptr.getNode()->hasOneUse())
8068     return false;
8069
8070   for (SDNode *Op : Ptr.getNode()->uses()) {
8071     if (Op == N ||
8072         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
8073       continue;
8074
8075     SDValue BasePtr;
8076     SDValue Offset;
8077     ISD::MemIndexedMode AM = ISD::UNINDEXED;
8078     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
8079       // Don't create a indexed load / store with zero offset.
8080       if (isa<ConstantSDNode>(Offset) &&
8081           cast<ConstantSDNode>(Offset)->isNullValue())
8082         continue;
8083
8084       // Try turning it into a post-indexed load / store except when
8085       // 1) All uses are load / store ops that use it as base ptr (and
8086       //    it may be folded as addressing mmode).
8087       // 2) Op must be independent of N, i.e. Op is neither a predecessor
8088       //    nor a successor of N. Otherwise, if Op is folded that would
8089       //    create a cycle.
8090
8091       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
8092         continue;
8093
8094       // Check for #1.
8095       bool TryNext = false;
8096       for (SDNode *Use : BasePtr.getNode()->uses()) {
8097         if (Use == Ptr.getNode())
8098           continue;
8099
8100         // If all the uses are load / store addresses, then don't do the
8101         // transformation.
8102         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
8103           bool RealUse = false;
8104           for (SDNode *UseUse : Use->uses()) {
8105             if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
8106               RealUse = true;
8107           }
8108
8109           if (!RealUse) {
8110             TryNext = true;
8111             break;
8112           }
8113         }
8114       }
8115
8116       if (TryNext)
8117         continue;
8118
8119       // Check for #2
8120       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
8121         SDValue Result = isLoad
8122           ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
8123                                BasePtr, Offset, AM)
8124           : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
8125                                 BasePtr, Offset, AM);
8126         ++PostIndexedNodes;
8127         ++NodesCombined;
8128         DEBUG(dbgs() << "\nReplacing.5 ";
8129               N->dump(&DAG);
8130               dbgs() << "\nWith: ";
8131               Result.getNode()->dump(&DAG);
8132               dbgs() << '\n');
8133         WorklistRemover DeadNodes(*this);
8134         if (isLoad) {
8135           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
8136           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
8137         } else {
8138           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
8139         }
8140
8141         // Finally, since the node is now dead, remove it from the graph.
8142         deleteAndRecombine(N);
8143
8144         // Replace the uses of Use with uses of the updated base value.
8145         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
8146                                       Result.getValue(isLoad ? 1 : 0));
8147         deleteAndRecombine(Op);
8148         return true;
8149       }
8150     }
8151   }
8152
8153   return false;
8154 }
8155
8156 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
8157 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
8158   ISD::MemIndexedMode AM = LD->getAddressingMode();
8159   assert(AM != ISD::UNINDEXED);
8160   SDValue BP = LD->getOperand(1);
8161   SDValue Inc = LD->getOperand(2);
8162
8163   // Some backends use TargetConstants for load offsets, but don't expect
8164   // TargetConstants in general ADD nodes. We can convert these constants into
8165   // regular Constants (if the constant is not opaque).
8166   assert((Inc.getOpcode() != ISD::TargetConstant ||
8167           !cast<ConstantSDNode>(Inc)->isOpaque()) &&
8168          "Cannot split out indexing using opaque target constants");
8169   if (Inc.getOpcode() == ISD::TargetConstant) {
8170     ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
8171     Inc = DAG.getConstant(*ConstInc->getConstantIntValue(),
8172                           ConstInc->getValueType(0));
8173   }
8174
8175   unsigned Opc =
8176       (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
8177   return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
8178 }
8179
8180 SDValue DAGCombiner::visitLOAD(SDNode *N) {
8181   LoadSDNode *LD  = cast<LoadSDNode>(N);
8182   SDValue Chain = LD->getChain();
8183   SDValue Ptr   = LD->getBasePtr();
8184
8185   // If load is not volatile and there are no uses of the loaded value (and
8186   // the updated indexed value in case of indexed loads), change uses of the
8187   // chain value into uses of the chain input (i.e. delete the dead load).
8188   if (!LD->isVolatile()) {
8189     if (N->getValueType(1) == MVT::Other) {
8190       // Unindexed loads.
8191       if (!N->hasAnyUseOfValue(0)) {
8192         // It's not safe to use the two value CombineTo variant here. e.g.
8193         // v1, chain2 = load chain1, loc
8194         // v2, chain3 = load chain2, loc
8195         // v3         = add v2, c
8196         // Now we replace use of chain2 with chain1.  This makes the second load
8197         // isomorphic to the one we are deleting, and thus makes this load live.
8198         DEBUG(dbgs() << "\nReplacing.6 ";
8199               N->dump(&DAG);
8200               dbgs() << "\nWith chain: ";
8201               Chain.getNode()->dump(&DAG);
8202               dbgs() << "\n");
8203         WorklistRemover DeadNodes(*this);
8204         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8205
8206         if (N->use_empty())
8207           deleteAndRecombine(N);
8208
8209         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8210       }
8211     } else {
8212       // Indexed loads.
8213       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
8214
8215       // If this load has an opaque TargetConstant offset, then we cannot split
8216       // the indexing into an add/sub directly (that TargetConstant may not be
8217       // valid for a different type of node, and we cannot convert an opaque
8218       // target constant into a regular constant).
8219       bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
8220                        cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
8221
8222       if (!N->hasAnyUseOfValue(0) &&
8223           ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
8224         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
8225         SDValue Index;
8226         if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
8227           Index = SplitIndexingFromLoad(LD);
8228           // Try to fold the base pointer arithmetic into subsequent loads and
8229           // stores.
8230           AddUsersToWorklist(N);
8231         } else
8232           Index = DAG.getUNDEF(N->getValueType(1));
8233         DEBUG(dbgs() << "\nReplacing.7 ";
8234               N->dump(&DAG);
8235               dbgs() << "\nWith: ";
8236               Undef.getNode()->dump(&DAG);
8237               dbgs() << " and 2 other values\n");
8238         WorklistRemover DeadNodes(*this);
8239         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
8240         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
8241         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
8242         deleteAndRecombine(N);
8243         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8244       }
8245     }
8246   }
8247
8248   // If this load is directly stored, replace the load value with the stored
8249   // value.
8250   // TODO: Handle store large -> read small portion.
8251   // TODO: Handle TRUNCSTORE/LOADEXT
8252   if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
8253     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
8254       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
8255       if (PrevST->getBasePtr() == Ptr &&
8256           PrevST->getValue().getValueType() == N->getValueType(0))
8257       return CombineTo(N, Chain.getOperand(1), Chain);
8258     }
8259   }
8260
8261   // Try to infer better alignment information than the load already has.
8262   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
8263     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
8264       if (Align > LD->getMemOperand()->getBaseAlignment()) {
8265         SDValue NewLoad =
8266                DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
8267                               LD->getValueType(0),
8268                               Chain, Ptr, LD->getPointerInfo(),
8269                               LD->getMemoryVT(),
8270                               LD->isVolatile(), LD->isNonTemporal(),
8271                               LD->isInvariant(), Align, LD->getAAInfo());
8272         return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
8273       }
8274     }
8275   }
8276
8277   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
8278                                                   : DAG.getSubtarget().useAA();
8279 #ifndef NDEBUG
8280   if (CombinerAAOnlyFunc.getNumOccurrences() &&
8281       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
8282     UseAA = false;
8283 #endif
8284   if (UseAA && LD->isUnindexed()) {
8285     // Walk up chain skipping non-aliasing memory nodes.
8286     SDValue BetterChain = FindBetterChain(N, Chain);
8287
8288     // If there is a better chain.
8289     if (Chain != BetterChain) {
8290       SDValue ReplLoad;
8291
8292       // Replace the chain to void dependency.
8293       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
8294         ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
8295                                BetterChain, Ptr, LD->getMemOperand());
8296       } else {
8297         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
8298                                   LD->getValueType(0),
8299                                   BetterChain, Ptr, LD->getMemoryVT(),
8300                                   LD->getMemOperand());
8301       }
8302
8303       // Create token factor to keep old chain connected.
8304       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
8305                                   MVT::Other, Chain, ReplLoad.getValue(1));
8306
8307       // Make sure the new and old chains are cleaned up.
8308       AddToWorklist(Token.getNode());
8309
8310       // Replace uses with load result and token factor. Don't add users
8311       // to work list.
8312       return CombineTo(N, ReplLoad.getValue(0), Token, false);
8313     }
8314   }
8315
8316   // Try transforming N to an indexed load.
8317   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
8318     return SDValue(N, 0);
8319
8320   // Try to slice up N to more direct loads if the slices are mapped to
8321   // different register banks or pairing can take place.
8322   if (SliceUpLoad(N))
8323     return SDValue(N, 0);
8324
8325   return SDValue();
8326 }
8327
8328 namespace {
8329 /// \brief Helper structure used to slice a load in smaller loads.
8330 /// Basically a slice is obtained from the following sequence:
8331 /// Origin = load Ty1, Base
8332 /// Shift = srl Ty1 Origin, CstTy Amount
8333 /// Inst = trunc Shift to Ty2
8334 ///
8335 /// Then, it will be rewriten into:
8336 /// Slice = load SliceTy, Base + SliceOffset
8337 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
8338 ///
8339 /// SliceTy is deduced from the number of bits that are actually used to
8340 /// build Inst.
8341 struct LoadedSlice {
8342   /// \brief Helper structure used to compute the cost of a slice.
8343   struct Cost {
8344     /// Are we optimizing for code size.
8345     bool ForCodeSize;
8346     /// Various cost.
8347     unsigned Loads;
8348     unsigned Truncates;
8349     unsigned CrossRegisterBanksCopies;
8350     unsigned ZExts;
8351     unsigned Shift;
8352
8353     Cost(bool ForCodeSize = false)
8354         : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
8355           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
8356
8357     /// \brief Get the cost of one isolated slice.
8358     Cost(const LoadedSlice &LS, bool ForCodeSize = false)
8359         : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
8360           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
8361       EVT TruncType = LS.Inst->getValueType(0);
8362       EVT LoadedType = LS.getLoadedType();
8363       if (TruncType != LoadedType &&
8364           !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
8365         ZExts = 1;
8366     }
8367
8368     /// \brief Account for slicing gain in the current cost.
8369     /// Slicing provide a few gains like removing a shift or a
8370     /// truncate. This method allows to grow the cost of the original
8371     /// load with the gain from this slice.
8372     void addSliceGain(const LoadedSlice &LS) {
8373       // Each slice saves a truncate.
8374       const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
8375       if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
8376                               LS.Inst->getOperand(0).getValueType()))
8377         ++Truncates;
8378       // If there is a shift amount, this slice gets rid of it.
8379       if (LS.Shift)
8380         ++Shift;
8381       // If this slice can merge a cross register bank copy, account for it.
8382       if (LS.canMergeExpensiveCrossRegisterBankCopy())
8383         ++CrossRegisterBanksCopies;
8384     }
8385
8386     Cost &operator+=(const Cost &RHS) {
8387       Loads += RHS.Loads;
8388       Truncates += RHS.Truncates;
8389       CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
8390       ZExts += RHS.ZExts;
8391       Shift += RHS.Shift;
8392       return *this;
8393     }
8394
8395     bool operator==(const Cost &RHS) const {
8396       return Loads == RHS.Loads && Truncates == RHS.Truncates &&
8397              CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
8398              ZExts == RHS.ZExts && Shift == RHS.Shift;
8399     }
8400
8401     bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
8402
8403     bool operator<(const Cost &RHS) const {
8404       // Assume cross register banks copies are as expensive as loads.
8405       // FIXME: Do we want some more target hooks?
8406       unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
8407       unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
8408       // Unless we are optimizing for code size, consider the
8409       // expensive operation first.
8410       if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
8411         return ExpensiveOpsLHS < ExpensiveOpsRHS;
8412       return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
8413              (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
8414     }
8415
8416     bool operator>(const Cost &RHS) const { return RHS < *this; }
8417
8418     bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
8419
8420     bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
8421   };
8422   // The last instruction that represent the slice. This should be a
8423   // truncate instruction.
8424   SDNode *Inst;
8425   // The original load instruction.
8426   LoadSDNode *Origin;
8427   // The right shift amount in bits from the original load.
8428   unsigned Shift;
8429   // The DAG from which Origin came from.
8430   // This is used to get some contextual information about legal types, etc.
8431   SelectionDAG *DAG;
8432
8433   LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
8434               unsigned Shift = 0, SelectionDAG *DAG = nullptr)
8435       : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
8436
8437   LoadedSlice(const LoadedSlice &LS)
8438       : Inst(LS.Inst), Origin(LS.Origin), Shift(LS.Shift), DAG(LS.DAG) {}
8439
8440   /// \brief Get the bits used in a chunk of bits \p BitWidth large.
8441   /// \return Result is \p BitWidth and has used bits set to 1 and
8442   ///         not used bits set to 0.
8443   APInt getUsedBits() const {
8444     // Reproduce the trunc(lshr) sequence:
8445     // - Start from the truncated value.
8446     // - Zero extend to the desired bit width.
8447     // - Shift left.
8448     assert(Origin && "No original load to compare against.");
8449     unsigned BitWidth = Origin->getValueSizeInBits(0);
8450     assert(Inst && "This slice is not bound to an instruction");
8451     assert(Inst->getValueSizeInBits(0) <= BitWidth &&
8452            "Extracted slice is bigger than the whole type!");
8453     APInt UsedBits(Inst->getValueSizeInBits(0), 0);
8454     UsedBits.setAllBits();
8455     UsedBits = UsedBits.zext(BitWidth);
8456     UsedBits <<= Shift;
8457     return UsedBits;
8458   }
8459
8460   /// \brief Get the size of the slice to be loaded in bytes.
8461   unsigned getLoadedSize() const {
8462     unsigned SliceSize = getUsedBits().countPopulation();
8463     assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
8464     return SliceSize / 8;
8465   }
8466
8467   /// \brief Get the type that will be loaded for this slice.
8468   /// Note: This may not be the final type for the slice.
8469   EVT getLoadedType() const {
8470     assert(DAG && "Missing context");
8471     LLVMContext &Ctxt = *DAG->getContext();
8472     return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
8473   }
8474
8475   /// \brief Get the alignment of the load used for this slice.
8476   unsigned getAlignment() const {
8477     unsigned Alignment = Origin->getAlignment();
8478     unsigned Offset = getOffsetFromBase();
8479     if (Offset != 0)
8480       Alignment = MinAlign(Alignment, Alignment + Offset);
8481     return Alignment;
8482   }
8483
8484   /// \brief Check if this slice can be rewritten with legal operations.
8485   bool isLegal() const {
8486     // An invalid slice is not legal.
8487     if (!Origin || !Inst || !DAG)
8488       return false;
8489
8490     // Offsets are for indexed load only, we do not handle that.
8491     if (Origin->getOffset().getOpcode() != ISD::UNDEF)
8492       return false;
8493
8494     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8495
8496     // Check that the type is legal.
8497     EVT SliceType = getLoadedType();
8498     if (!TLI.isTypeLegal(SliceType))
8499       return false;
8500
8501     // Check that the load is legal for this type.
8502     if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
8503       return false;
8504
8505     // Check that the offset can be computed.
8506     // 1. Check its type.
8507     EVT PtrType = Origin->getBasePtr().getValueType();
8508     if (PtrType == MVT::Untyped || PtrType.isExtended())
8509       return false;
8510
8511     // 2. Check that it fits in the immediate.
8512     if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
8513       return false;
8514
8515     // 3. Check that the computation is legal.
8516     if (!TLI.isOperationLegal(ISD::ADD, PtrType))
8517       return false;
8518
8519     // Check that the zext is legal if it needs one.
8520     EVT TruncateType = Inst->getValueType(0);
8521     if (TruncateType != SliceType &&
8522         !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
8523       return false;
8524
8525     return true;
8526   }
8527
8528   /// \brief Get the offset in bytes of this slice in the original chunk of
8529   /// bits.
8530   /// \pre DAG != nullptr.
8531   uint64_t getOffsetFromBase() const {
8532     assert(DAG && "Missing context.");
8533     bool IsBigEndian =
8534         DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
8535     assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
8536     uint64_t Offset = Shift / 8;
8537     unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
8538     assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
8539            "The size of the original loaded type is not a multiple of a"
8540            " byte.");
8541     // If Offset is bigger than TySizeInBytes, it means we are loading all
8542     // zeros. This should have been optimized before in the process.
8543     assert(TySizeInBytes > Offset &&
8544            "Invalid shift amount for given loaded size");
8545     if (IsBigEndian)
8546       Offset = TySizeInBytes - Offset - getLoadedSize();
8547     return Offset;
8548   }
8549
8550   /// \brief Generate the sequence of instructions to load the slice
8551   /// represented by this object and redirect the uses of this slice to
8552   /// this new sequence of instructions.
8553   /// \pre this->Inst && this->Origin are valid Instructions and this
8554   /// object passed the legal check: LoadedSlice::isLegal returned true.
8555   /// \return The last instruction of the sequence used to load the slice.
8556   SDValue loadSlice() const {
8557     assert(Inst && Origin && "Unable to replace a non-existing slice.");
8558     const SDValue &OldBaseAddr = Origin->getBasePtr();
8559     SDValue BaseAddr = OldBaseAddr;
8560     // Get the offset in that chunk of bytes w.r.t. the endianess.
8561     int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
8562     assert(Offset >= 0 && "Offset too big to fit in int64_t!");
8563     if (Offset) {
8564       // BaseAddr = BaseAddr + Offset.
8565       EVT ArithType = BaseAddr.getValueType();
8566       BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
8567                               DAG->getConstant(Offset, ArithType));
8568     }
8569
8570     // Create the type of the loaded slice according to its size.
8571     EVT SliceType = getLoadedType();
8572
8573     // Create the load for the slice.
8574     SDValue LastInst = DAG->getLoad(
8575         SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
8576         Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
8577         Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
8578     // If the final type is not the same as the loaded type, this means that
8579     // we have to pad with zero. Create a zero extend for that.
8580     EVT FinalType = Inst->getValueType(0);
8581     if (SliceType != FinalType)
8582       LastInst =
8583           DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
8584     return LastInst;
8585   }
8586
8587   /// \brief Check if this slice can be merged with an expensive cross register
8588   /// bank copy. E.g.,
8589   /// i = load i32
8590   /// f = bitcast i32 i to float
8591   bool canMergeExpensiveCrossRegisterBankCopy() const {
8592     if (!Inst || !Inst->hasOneUse())
8593       return false;
8594     SDNode *Use = *Inst->use_begin();
8595     if (Use->getOpcode() != ISD::BITCAST)
8596       return false;
8597     assert(DAG && "Missing context");
8598     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8599     EVT ResVT = Use->getValueType(0);
8600     const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
8601     const TargetRegisterClass *ArgRC =
8602         TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
8603     if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
8604       return false;
8605
8606     // At this point, we know that we perform a cross-register-bank copy.
8607     // Check if it is expensive.
8608     const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
8609     // Assume bitcasts are cheap, unless both register classes do not
8610     // explicitly share a common sub class.
8611     if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
8612       return false;
8613
8614     // Check if it will be merged with the load.
8615     // 1. Check the alignment constraint.
8616     unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
8617         ResVT.getTypeForEVT(*DAG->getContext()));
8618
8619     if (RequiredAlignment > getAlignment())
8620       return false;
8621
8622     // 2. Check that the load is a legal operation for that type.
8623     if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
8624       return false;
8625
8626     // 3. Check that we do not have a zext in the way.
8627     if (Inst->getValueType(0) != getLoadedType())
8628       return false;
8629
8630     return true;
8631   }
8632 };
8633 }
8634
8635 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
8636 /// \p UsedBits looks like 0..0 1..1 0..0.
8637 static bool areUsedBitsDense(const APInt &UsedBits) {
8638   // If all the bits are one, this is dense!
8639   if (UsedBits.isAllOnesValue())
8640     return true;
8641
8642   // Get rid of the unused bits on the right.
8643   APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
8644   // Get rid of the unused bits on the left.
8645   if (NarrowedUsedBits.countLeadingZeros())
8646     NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
8647   // Check that the chunk of bits is completely used.
8648   return NarrowedUsedBits.isAllOnesValue();
8649 }
8650
8651 /// \brief Check whether or not \p First and \p Second are next to each other
8652 /// in memory. This means that there is no hole between the bits loaded
8653 /// by \p First and the bits loaded by \p Second.
8654 static bool areSlicesNextToEachOther(const LoadedSlice &First,
8655                                      const LoadedSlice &Second) {
8656   assert(First.Origin == Second.Origin && First.Origin &&
8657          "Unable to match different memory origins.");
8658   APInt UsedBits = First.getUsedBits();
8659   assert((UsedBits & Second.getUsedBits()) == 0 &&
8660          "Slices are not supposed to overlap.");
8661   UsedBits |= Second.getUsedBits();
8662   return areUsedBitsDense(UsedBits);
8663 }
8664
8665 /// \brief Adjust the \p GlobalLSCost according to the target
8666 /// paring capabilities and the layout of the slices.
8667 /// \pre \p GlobalLSCost should account for at least as many loads as
8668 /// there is in the slices in \p LoadedSlices.
8669 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8670                                  LoadedSlice::Cost &GlobalLSCost) {
8671   unsigned NumberOfSlices = LoadedSlices.size();
8672   // If there is less than 2 elements, no pairing is possible.
8673   if (NumberOfSlices < 2)
8674     return;
8675
8676   // Sort the slices so that elements that are likely to be next to each
8677   // other in memory are next to each other in the list.
8678   std::sort(LoadedSlices.begin(), LoadedSlices.end(),
8679             [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
8680     assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
8681     return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
8682   });
8683   const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
8684   // First (resp. Second) is the first (resp. Second) potentially candidate
8685   // to be placed in a paired load.
8686   const LoadedSlice *First = nullptr;
8687   const LoadedSlice *Second = nullptr;
8688   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
8689                 // Set the beginning of the pair.
8690                                                            First = Second) {
8691
8692     Second = &LoadedSlices[CurrSlice];
8693
8694     // If First is NULL, it means we start a new pair.
8695     // Get to the next slice.
8696     if (!First)
8697       continue;
8698
8699     EVT LoadedType = First->getLoadedType();
8700
8701     // If the types of the slices are different, we cannot pair them.
8702     if (LoadedType != Second->getLoadedType())
8703       continue;
8704
8705     // Check if the target supplies paired loads for this type.
8706     unsigned RequiredAlignment = 0;
8707     if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
8708       // move to the next pair, this type is hopeless.
8709       Second = nullptr;
8710       continue;
8711     }
8712     // Check if we meet the alignment requirement.
8713     if (RequiredAlignment > First->getAlignment())
8714       continue;
8715
8716     // Check that both loads are next to each other in memory.
8717     if (!areSlicesNextToEachOther(*First, *Second))
8718       continue;
8719
8720     assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
8721     --GlobalLSCost.Loads;
8722     // Move to the next pair.
8723     Second = nullptr;
8724   }
8725 }
8726
8727 /// \brief Check the profitability of all involved LoadedSlice.
8728 /// Currently, it is considered profitable if there is exactly two
8729 /// involved slices (1) which are (2) next to each other in memory, and
8730 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
8731 ///
8732 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
8733 /// the elements themselves.
8734 ///
8735 /// FIXME: When the cost model will be mature enough, we can relax
8736 /// constraints (1) and (2).
8737 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8738                                 const APInt &UsedBits, bool ForCodeSize) {
8739   unsigned NumberOfSlices = LoadedSlices.size();
8740   if (StressLoadSlicing)
8741     return NumberOfSlices > 1;
8742
8743   // Check (1).
8744   if (NumberOfSlices != 2)
8745     return false;
8746
8747   // Check (2).
8748   if (!areUsedBitsDense(UsedBits))
8749     return false;
8750
8751   // Check (3).
8752   LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
8753   // The original code has one big load.
8754   OrigCost.Loads = 1;
8755   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
8756     const LoadedSlice &LS = LoadedSlices[CurrSlice];
8757     // Accumulate the cost of all the slices.
8758     LoadedSlice::Cost SliceCost(LS, ForCodeSize);
8759     GlobalSlicingCost += SliceCost;
8760
8761     // Account as cost in the original configuration the gain obtained
8762     // with the current slices.
8763     OrigCost.addSliceGain(LS);
8764   }
8765
8766   // If the target supports paired load, adjust the cost accordingly.
8767   adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
8768   return OrigCost > GlobalSlicingCost;
8769 }
8770
8771 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
8772 /// operations, split it in the various pieces being extracted.
8773 ///
8774 /// This sort of thing is introduced by SROA.
8775 /// This slicing takes care not to insert overlapping loads.
8776 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
8777 bool DAGCombiner::SliceUpLoad(SDNode *N) {
8778   if (Level < AfterLegalizeDAG)
8779     return false;
8780
8781   LoadSDNode *LD = cast<LoadSDNode>(N);
8782   if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
8783       !LD->getValueType(0).isInteger())
8784     return false;
8785
8786   // Keep track of already used bits to detect overlapping values.
8787   // In that case, we will just abort the transformation.
8788   APInt UsedBits(LD->getValueSizeInBits(0), 0);
8789
8790   SmallVector<LoadedSlice, 4> LoadedSlices;
8791
8792   // Check if this load is used as several smaller chunks of bits.
8793   // Basically, look for uses in trunc or trunc(lshr) and record a new chain
8794   // of computation for each trunc.
8795   for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
8796        UI != UIEnd; ++UI) {
8797     // Skip the uses of the chain.
8798     if (UI.getUse().getResNo() != 0)
8799       continue;
8800
8801     SDNode *User = *UI;
8802     unsigned Shift = 0;
8803
8804     // Check if this is a trunc(lshr).
8805     if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
8806         isa<ConstantSDNode>(User->getOperand(1))) {
8807       Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
8808       User = *User->use_begin();
8809     }
8810
8811     // At this point, User is a Truncate, iff we encountered, trunc or
8812     // trunc(lshr).
8813     if (User->getOpcode() != ISD::TRUNCATE)
8814       return false;
8815
8816     // The width of the type must be a power of 2 and greater than 8-bits.
8817     // Otherwise the load cannot be represented in LLVM IR.
8818     // Moreover, if we shifted with a non-8-bits multiple, the slice
8819     // will be across several bytes. We do not support that.
8820     unsigned Width = User->getValueSizeInBits(0);
8821     if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
8822       return 0;
8823
8824     // Build the slice for this chain of computations.
8825     LoadedSlice LS(User, LD, Shift, &DAG);
8826     APInt CurrentUsedBits = LS.getUsedBits();
8827
8828     // Check if this slice overlaps with another.
8829     if ((CurrentUsedBits & UsedBits) != 0)
8830       return false;
8831     // Update the bits used globally.
8832     UsedBits |= CurrentUsedBits;
8833
8834     // Check if the new slice would be legal.
8835     if (!LS.isLegal())
8836       return false;
8837
8838     // Record the slice.
8839     LoadedSlices.push_back(LS);
8840   }
8841
8842   // Abort slicing if it does not seem to be profitable.
8843   if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
8844     return false;
8845
8846   ++SlicedLoads;
8847
8848   // Rewrite each chain to use an independent load.
8849   // By construction, each chain can be represented by a unique load.
8850
8851   // Prepare the argument for the new token factor for all the slices.
8852   SmallVector<SDValue, 8> ArgChains;
8853   for (SmallVectorImpl<LoadedSlice>::const_iterator
8854            LSIt = LoadedSlices.begin(),
8855            LSItEnd = LoadedSlices.end();
8856        LSIt != LSItEnd; ++LSIt) {
8857     SDValue SliceInst = LSIt->loadSlice();
8858     CombineTo(LSIt->Inst, SliceInst, true);
8859     if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
8860       SliceInst = SliceInst.getOperand(0);
8861     assert(SliceInst->getOpcode() == ISD::LOAD &&
8862            "It takes more than a zext to get to the loaded slice!!");
8863     ArgChains.push_back(SliceInst.getValue(1));
8864   }
8865
8866   SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
8867                               ArgChains);
8868   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8869   return true;
8870 }
8871
8872 /// Check to see if V is (and load (ptr), imm), where the load is having
8873 /// specific bytes cleared out.  If so, return the byte size being masked out
8874 /// and the shift amount.
8875 static std::pair<unsigned, unsigned>
8876 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
8877   std::pair<unsigned, unsigned> Result(0, 0);
8878
8879   // Check for the structure we're looking for.
8880   if (V->getOpcode() != ISD::AND ||
8881       !isa<ConstantSDNode>(V->getOperand(1)) ||
8882       !ISD::isNormalLoad(V->getOperand(0).getNode()))
8883     return Result;
8884
8885   // Check the chain and pointer.
8886   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
8887   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
8888
8889   // The store should be chained directly to the load or be an operand of a
8890   // tokenfactor.
8891   if (LD == Chain.getNode())
8892     ; // ok.
8893   else if (Chain->getOpcode() != ISD::TokenFactor)
8894     return Result; // Fail.
8895   else {
8896     bool isOk = false;
8897     for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
8898       if (Chain->getOperand(i).getNode() == LD) {
8899         isOk = true;
8900         break;
8901       }
8902     if (!isOk) return Result;
8903   }
8904
8905   // This only handles simple types.
8906   if (V.getValueType() != MVT::i16 &&
8907       V.getValueType() != MVT::i32 &&
8908       V.getValueType() != MVT::i64)
8909     return Result;
8910
8911   // Check the constant mask.  Invert it so that the bits being masked out are
8912   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
8913   // follow the sign bit for uniformity.
8914   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
8915   unsigned NotMaskLZ = countLeadingZeros(NotMask);
8916   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
8917   unsigned NotMaskTZ = countTrailingZeros(NotMask);
8918   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
8919   if (NotMaskLZ == 64) return Result;  // All zero mask.
8920
8921   // See if we have a continuous run of bits.  If so, we have 0*1+0*
8922   if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
8923     return Result;
8924
8925   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
8926   if (V.getValueType() != MVT::i64 && NotMaskLZ)
8927     NotMaskLZ -= 64-V.getValueSizeInBits();
8928
8929   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
8930   switch (MaskedBytes) {
8931   case 1:
8932   case 2:
8933   case 4: break;
8934   default: return Result; // All one mask, or 5-byte mask.
8935   }
8936
8937   // Verify that the first bit starts at a multiple of mask so that the access
8938   // is aligned the same as the access width.
8939   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
8940
8941   Result.first = MaskedBytes;
8942   Result.second = NotMaskTZ/8;
8943   return Result;
8944 }
8945
8946
8947 /// Check to see if IVal is something that provides a value as specified by
8948 /// MaskInfo. If so, replace the specified store with a narrower store of
8949 /// truncated IVal.
8950 static SDNode *
8951 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
8952                                 SDValue IVal, StoreSDNode *St,
8953                                 DAGCombiner *DC) {
8954   unsigned NumBytes = MaskInfo.first;
8955   unsigned ByteShift = MaskInfo.second;
8956   SelectionDAG &DAG = DC->getDAG();
8957
8958   // Check to see if IVal is all zeros in the part being masked in by the 'or'
8959   // that uses this.  If not, this is not a replacement.
8960   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
8961                                   ByteShift*8, (ByteShift+NumBytes)*8);
8962   if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
8963
8964   // Check that it is legal on the target to do this.  It is legal if the new
8965   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
8966   // legalization.
8967   MVT VT = MVT::getIntegerVT(NumBytes*8);
8968   if (!DC->isTypeLegal(VT))
8969     return nullptr;
8970
8971   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
8972   // shifted by ByteShift and truncated down to NumBytes.
8973   if (ByteShift)
8974     IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
8975                        DAG.getConstant(ByteShift*8,
8976                                     DC->getShiftAmountTy(IVal.getValueType())));
8977
8978   // Figure out the offset for the store and the alignment of the access.
8979   unsigned StOffset;
8980   unsigned NewAlign = St->getAlignment();
8981
8982   if (DAG.getTargetLoweringInfo().isLittleEndian())
8983     StOffset = ByteShift;
8984   else
8985     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
8986
8987   SDValue Ptr = St->getBasePtr();
8988   if (StOffset) {
8989     Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
8990                       Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
8991     NewAlign = MinAlign(NewAlign, StOffset);
8992   }
8993
8994   // Truncate down to the new size.
8995   IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
8996
8997   ++OpsNarrowed;
8998   return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
8999                       St->getPointerInfo().getWithOffset(StOffset),
9000                       false, false, NewAlign).getNode();
9001 }
9002
9003
9004 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
9005 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
9006 /// narrowing the load and store if it would end up being a win for performance
9007 /// or code size.
9008 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
9009   StoreSDNode *ST  = cast<StoreSDNode>(N);
9010   if (ST->isVolatile())
9011     return SDValue();
9012
9013   SDValue Chain = ST->getChain();
9014   SDValue Value = ST->getValue();
9015   SDValue Ptr   = ST->getBasePtr();
9016   EVT VT = Value.getValueType();
9017
9018   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
9019     return SDValue();
9020
9021   unsigned Opc = Value.getOpcode();
9022
9023   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
9024   // is a byte mask indicating a consecutive number of bytes, check to see if
9025   // Y is known to provide just those bytes.  If so, we try to replace the
9026   // load + replace + store sequence with a single (narrower) store, which makes
9027   // the load dead.
9028   if (Opc == ISD::OR) {
9029     std::pair<unsigned, unsigned> MaskedLoad;
9030     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
9031     if (MaskedLoad.first)
9032       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
9033                                                   Value.getOperand(1), ST,this))
9034         return SDValue(NewST, 0);
9035
9036     // Or is commutative, so try swapping X and Y.
9037     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
9038     if (MaskedLoad.first)
9039       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
9040                                                   Value.getOperand(0), ST,this))
9041         return SDValue(NewST, 0);
9042   }
9043
9044   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
9045       Value.getOperand(1).getOpcode() != ISD::Constant)
9046     return SDValue();
9047
9048   SDValue N0 = Value.getOperand(0);
9049   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
9050       Chain == SDValue(N0.getNode(), 1)) {
9051     LoadSDNode *LD = cast<LoadSDNode>(N0);
9052     if (LD->getBasePtr() != Ptr ||
9053         LD->getPointerInfo().getAddrSpace() !=
9054         ST->getPointerInfo().getAddrSpace())
9055       return SDValue();
9056
9057     // Find the type to narrow it the load / op / store to.
9058     SDValue N1 = Value.getOperand(1);
9059     unsigned BitWidth = N1.getValueSizeInBits();
9060     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
9061     if (Opc == ISD::AND)
9062       Imm ^= APInt::getAllOnesValue(BitWidth);
9063     if (Imm == 0 || Imm.isAllOnesValue())
9064       return SDValue();
9065     unsigned ShAmt = Imm.countTrailingZeros();
9066     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
9067     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
9068     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
9069     while (NewBW < BitWidth &&
9070            !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
9071              TLI.isNarrowingProfitable(VT, NewVT))) {
9072       NewBW = NextPowerOf2(NewBW);
9073       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
9074     }
9075     if (NewBW >= BitWidth)
9076       return SDValue();
9077
9078     // If the lsb changed does not start at the type bitwidth boundary,
9079     // start at the previous one.
9080     if (ShAmt % NewBW)
9081       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
9082     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
9083                                    std::min(BitWidth, ShAmt + NewBW));
9084     if ((Imm & Mask) == Imm) {
9085       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
9086       if (Opc == ISD::AND)
9087         NewImm ^= APInt::getAllOnesValue(NewBW);
9088       uint64_t PtrOff = ShAmt / 8;
9089       // For big endian targets, we need to adjust the offset to the pointer to
9090       // load the correct bytes.
9091       if (TLI.isBigEndian())
9092         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
9093
9094       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
9095       Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
9096       if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
9097         return SDValue();
9098
9099       SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
9100                                    Ptr.getValueType(), Ptr,
9101                                    DAG.getConstant(PtrOff, Ptr.getValueType()));
9102       SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
9103                                   LD->getChain(), NewPtr,
9104                                   LD->getPointerInfo().getWithOffset(PtrOff),
9105                                   LD->isVolatile(), LD->isNonTemporal(),
9106                                   LD->isInvariant(), NewAlign,
9107                                   LD->getAAInfo());
9108       SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
9109                                    DAG.getConstant(NewImm, NewVT));
9110       SDValue NewST = DAG.getStore(Chain, SDLoc(N),
9111                                    NewVal, NewPtr,
9112                                    ST->getPointerInfo().getWithOffset(PtrOff),
9113                                    false, false, NewAlign);
9114
9115       AddToWorklist(NewPtr.getNode());
9116       AddToWorklist(NewLD.getNode());
9117       AddToWorklist(NewVal.getNode());
9118       WorklistRemover DeadNodes(*this);
9119       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
9120       ++OpsNarrowed;
9121       return NewST;
9122     }
9123   }
9124
9125   return SDValue();
9126 }
9127
9128 /// For a given floating point load / store pair, if the load value isn't used
9129 /// by any other operations, then consider transforming the pair to integer
9130 /// load / store operations if the target deems the transformation profitable.
9131 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
9132   StoreSDNode *ST  = cast<StoreSDNode>(N);
9133   SDValue Chain = ST->getChain();
9134   SDValue Value = ST->getValue();
9135   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
9136       Value.hasOneUse() &&
9137       Chain == SDValue(Value.getNode(), 1)) {
9138     LoadSDNode *LD = cast<LoadSDNode>(Value);
9139     EVT VT = LD->getMemoryVT();
9140     if (!VT.isFloatingPoint() ||
9141         VT != ST->getMemoryVT() ||
9142         LD->isNonTemporal() ||
9143         ST->isNonTemporal() ||
9144         LD->getPointerInfo().getAddrSpace() != 0 ||
9145         ST->getPointerInfo().getAddrSpace() != 0)
9146       return SDValue();
9147
9148     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
9149     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
9150         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
9151         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
9152         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
9153       return SDValue();
9154
9155     unsigned LDAlign = LD->getAlignment();
9156     unsigned STAlign = ST->getAlignment();
9157     Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
9158     unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
9159     if (LDAlign < ABIAlign || STAlign < ABIAlign)
9160       return SDValue();
9161
9162     SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
9163                                 LD->getChain(), LD->getBasePtr(),
9164                                 LD->getPointerInfo(),
9165                                 false, false, false, LDAlign);
9166
9167     SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
9168                                  NewLD, ST->getBasePtr(),
9169                                  ST->getPointerInfo(),
9170                                  false, false, STAlign);
9171
9172     AddToWorklist(NewLD.getNode());
9173     AddToWorklist(NewST.getNode());
9174     WorklistRemover DeadNodes(*this);
9175     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
9176     ++LdStFP2Int;
9177     return NewST;
9178   }
9179
9180   return SDValue();
9181 }
9182
9183 /// Helper struct to parse and store a memory address as base + index + offset.
9184 /// We ignore sign extensions when it is safe to do so.
9185 /// The following two expressions are not equivalent. To differentiate we need
9186 /// to store whether there was a sign extension involved in the index
9187 /// computation.
9188 ///  (load (i64 add (i64 copyfromreg %c)
9189 ///                 (i64 signextend (add (i8 load %index)
9190 ///                                      (i8 1))))
9191 /// vs
9192 ///
9193 /// (load (i64 add (i64 copyfromreg %c)
9194 ///                (i64 signextend (i32 add (i32 signextend (i8 load %index))
9195 ///                                         (i32 1)))))
9196 struct BaseIndexOffset {
9197   SDValue Base;
9198   SDValue Index;
9199   int64_t Offset;
9200   bool IsIndexSignExt;
9201
9202   BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
9203
9204   BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
9205                   bool IsIndexSignExt) :
9206     Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
9207
9208   bool equalBaseIndex(const BaseIndexOffset &Other) {
9209     return Other.Base == Base && Other.Index == Index &&
9210       Other.IsIndexSignExt == IsIndexSignExt;
9211   }
9212
9213   /// Parses tree in Ptr for base, index, offset addresses.
9214   static BaseIndexOffset match(SDValue Ptr) {
9215     bool IsIndexSignExt = false;
9216
9217     // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
9218     // instruction, then it could be just the BASE or everything else we don't
9219     // know how to handle. Just use Ptr as BASE and give up.
9220     if (Ptr->getOpcode() != ISD::ADD)
9221       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9222
9223     // We know that we have at least an ADD instruction. Try to pattern match
9224     // the simple case of BASE + OFFSET.
9225     if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
9226       int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
9227       return  BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
9228                               IsIndexSignExt);
9229     }
9230
9231     // Inside a loop the current BASE pointer is calculated using an ADD and a
9232     // MUL instruction. In this case Ptr is the actual BASE pointer.
9233     // (i64 add (i64 %array_ptr)
9234     //          (i64 mul (i64 %induction_var)
9235     //                   (i64 %element_size)))
9236     if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
9237       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9238
9239     // Look at Base + Index + Offset cases.
9240     SDValue Base = Ptr->getOperand(0);
9241     SDValue IndexOffset = Ptr->getOperand(1);
9242
9243     // Skip signextends.
9244     if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
9245       IndexOffset = IndexOffset->getOperand(0);
9246       IsIndexSignExt = true;
9247     }
9248
9249     // Either the case of Base + Index (no offset) or something else.
9250     if (IndexOffset->getOpcode() != ISD::ADD)
9251       return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
9252
9253     // Now we have the case of Base + Index + offset.
9254     SDValue Index = IndexOffset->getOperand(0);
9255     SDValue Offset = IndexOffset->getOperand(1);
9256
9257     if (!isa<ConstantSDNode>(Offset))
9258       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9259
9260     // Ignore signextends.
9261     if (Index->getOpcode() == ISD::SIGN_EXTEND) {
9262       Index = Index->getOperand(0);
9263       IsIndexSignExt = true;
9264     } else IsIndexSignExt = false;
9265
9266     int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
9267     return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
9268   }
9269 };
9270
9271 /// Holds a pointer to an LSBaseSDNode as well as information on where it
9272 /// is located in a sequence of memory operations connected by a chain.
9273 struct MemOpLink {
9274   MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
9275     MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
9276   // Ptr to the mem node.
9277   LSBaseSDNode *MemNode;
9278   // Offset from the base ptr.
9279   int64_t OffsetFromBase;
9280   // What is the sequence number of this mem node.
9281   // Lowest mem operand in the DAG starts at zero.
9282   unsigned SequenceNum;
9283 };
9284
9285 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
9286   EVT MemVT = St->getMemoryVT();
9287   int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
9288   bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes().
9289     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
9290
9291   // Don't merge vectors into wider inputs.
9292   if (MemVT.isVector() || !MemVT.isSimple())
9293     return false;
9294
9295   // Perform an early exit check. Do not bother looking at stored values that
9296   // are not constants or loads.
9297   SDValue StoredVal = St->getValue();
9298   bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
9299   if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) &&
9300       !IsLoadSrc)
9301     return false;
9302
9303   // Only look at ends of store sequences.
9304   SDValue Chain = SDValue(St, 0);
9305   if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
9306     return false;
9307
9308   // This holds the base pointer, index, and the offset in bytes from the base
9309   // pointer.
9310   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
9311
9312   // We must have a base and an offset.
9313   if (!BasePtr.Base.getNode())
9314     return false;
9315
9316   // Do not handle stores to undef base pointers.
9317   if (BasePtr.Base.getOpcode() == ISD::UNDEF)
9318     return false;
9319
9320   // Save the LoadSDNodes that we find in the chain.
9321   // We need to make sure that these nodes do not interfere with
9322   // any of the store nodes.
9323   SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
9324
9325   // Save the StoreSDNodes that we find in the chain.
9326   SmallVector<MemOpLink, 8> StoreNodes;
9327
9328   // Walk up the chain and look for nodes with offsets from the same
9329   // base pointer. Stop when reaching an instruction with a different kind
9330   // or instruction which has a different base pointer.
9331   unsigned Seq = 0;
9332   StoreSDNode *Index = St;
9333   while (Index) {
9334     // If the chain has more than one use, then we can't reorder the mem ops.
9335     if (Index != St && !SDValue(Index, 0)->hasOneUse())
9336       break;
9337
9338     // Find the base pointer and offset for this memory node.
9339     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
9340
9341     // Check that the base pointer is the same as the original one.
9342     if (!Ptr.equalBaseIndex(BasePtr))
9343       break;
9344
9345     // Check that the alignment is the same.
9346     if (Index->getAlignment() != St->getAlignment())
9347       break;
9348
9349     // The memory operands must not be volatile.
9350     if (Index->isVolatile() || Index->isIndexed())
9351       break;
9352
9353     // No truncation.
9354     if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
9355       if (St->isTruncatingStore())
9356         break;
9357
9358     // The stored memory type must be the same.
9359     if (Index->getMemoryVT() != MemVT)
9360       break;
9361
9362     // We do not allow unaligned stores because we want to prevent overriding
9363     // stores.
9364     if (Index->getAlignment()*8 != MemVT.getSizeInBits())
9365       break;
9366
9367     // We found a potential memory operand to merge.
9368     StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
9369
9370     // Find the next memory operand in the chain. If the next operand in the
9371     // chain is a store then move up and continue the scan with the next
9372     // memory operand. If the next operand is a load save it and use alias
9373     // information to check if it interferes with anything.
9374     SDNode *NextInChain = Index->getChain().getNode();
9375     while (1) {
9376       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
9377         // We found a store node. Use it for the next iteration.
9378         Index = STn;
9379         break;
9380       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
9381         if (Ldn->isVolatile()) {
9382           Index = nullptr;
9383           break;
9384         }
9385
9386         // Save the load node for later. Continue the scan.
9387         AliasLoadNodes.push_back(Ldn);
9388         NextInChain = Ldn->getChain().getNode();
9389         continue;
9390       } else {
9391         Index = nullptr;
9392         break;
9393       }
9394     }
9395   }
9396
9397   // Check if there is anything to merge.
9398   if (StoreNodes.size() < 2)
9399     return false;
9400
9401   // Sort the memory operands according to their distance from the base pointer.
9402   std::sort(StoreNodes.begin(), StoreNodes.end(),
9403             [](MemOpLink LHS, MemOpLink RHS) {
9404     return LHS.OffsetFromBase < RHS.OffsetFromBase ||
9405            (LHS.OffsetFromBase == RHS.OffsetFromBase &&
9406             LHS.SequenceNum > RHS.SequenceNum);
9407   });
9408
9409   // Scan the memory operations on the chain and find the first non-consecutive
9410   // store memory address.
9411   unsigned LastConsecutiveStore = 0;
9412   int64_t StartAddress = StoreNodes[0].OffsetFromBase;
9413   for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
9414
9415     // Check that the addresses are consecutive starting from the second
9416     // element in the list of stores.
9417     if (i > 0) {
9418       int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
9419       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9420         break;
9421     }
9422
9423     bool Alias = false;
9424     // Check if this store interferes with any of the loads that we found.
9425     for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
9426       if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
9427         Alias = true;
9428         break;
9429       }
9430     // We found a load that alias with this store. Stop the sequence.
9431     if (Alias)
9432       break;
9433
9434     // Mark this node as useful.
9435     LastConsecutiveStore = i;
9436   }
9437
9438   // The node with the lowest store address.
9439   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
9440
9441   // Store the constants into memory as one consecutive store.
9442   if (!IsLoadSrc) {
9443     unsigned LastLegalType = 0;
9444     unsigned LastLegalVectorType = 0;
9445     bool NonZero = false;
9446     for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9447       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
9448       SDValue StoredVal = St->getValue();
9449
9450       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
9451         NonZero |= !C->isNullValue();
9452       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
9453         NonZero |= !C->getConstantFPValue()->isNullValue();
9454       } else {
9455         // Non-constant.
9456         break;
9457       }
9458
9459       // Find a legal type for the constant store.
9460       unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9461       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9462       if (TLI.isTypeLegal(StoreTy))
9463         LastLegalType = i+1;
9464       // Or check whether a truncstore is legal.
9465       else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9466                TargetLowering::TypePromoteInteger) {
9467         EVT LegalizedStoredValueTy =
9468           TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
9469         if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
9470           LastLegalType = i+1;
9471       }
9472
9473       // Find a legal type for the vector store.
9474       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9475       if (TLI.isTypeLegal(Ty))
9476         LastLegalVectorType = i + 1;
9477     }
9478
9479     // We only use vectors if the constant is known to be zero and the
9480     // function is not marked with the noimplicitfloat attribute.
9481     if (NonZero || NoVectors)
9482       LastLegalVectorType = 0;
9483
9484     // Check if we found a legal integer type to store.
9485     if (LastLegalType == 0 && LastLegalVectorType == 0)
9486       return false;
9487
9488     bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
9489     unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
9490
9491     // Make sure we have something to merge.
9492     if (NumElem < 2)
9493       return false;
9494
9495     unsigned EarliestNodeUsed = 0;
9496     for (unsigned i=0; i < NumElem; ++i) {
9497       // Find a chain for the new wide-store operand. Notice that some
9498       // of the store nodes that we found may not be selected for inclusion
9499       // in the wide store. The chain we use needs to be the chain of the
9500       // earliest store node which is *used* and replaced by the wide store.
9501       if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9502         EarliestNodeUsed = i;
9503     }
9504
9505     // The earliest Node in the DAG.
9506     LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9507     SDLoc DL(StoreNodes[0].MemNode);
9508
9509     SDValue StoredVal;
9510     if (UseVector) {
9511       // Find a legal type for the vector store.
9512       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9513       assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
9514       StoredVal = DAG.getConstant(0, Ty);
9515     } else {
9516       unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9517       APInt StoreInt(StoreBW, 0);
9518
9519       // Construct a single integer constant which is made of the smaller
9520       // constant inputs.
9521       bool IsLE = TLI.isLittleEndian();
9522       for (unsigned i = 0; i < NumElem ; ++i) {
9523         unsigned Idx = IsLE ?(NumElem - 1 - i) : i;
9524         StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
9525         SDValue Val = St->getValue();
9526         StoreInt<<=ElementSizeBytes*8;
9527         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
9528           StoreInt|=C->getAPIntValue().zext(StoreBW);
9529         } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
9530           StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
9531         } else {
9532           assert(false && "Invalid constant element type");
9533         }
9534       }
9535
9536       // Create the new Load and Store operations.
9537       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9538       StoredVal = DAG.getConstant(StoreInt, StoreTy);
9539     }
9540
9541     SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
9542                                     FirstInChain->getBasePtr(),
9543                                     FirstInChain->getPointerInfo(),
9544                                     false, false,
9545                                     FirstInChain->getAlignment());
9546
9547     // Replace the first store with the new store
9548     CombineTo(EarliestOp, NewStore);
9549     // Erase all other stores.
9550     for (unsigned i = 0; i < NumElem ; ++i) {
9551       if (StoreNodes[i].MemNode == EarliestOp)
9552         continue;
9553       StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9554       // ReplaceAllUsesWith will replace all uses that existed when it was
9555       // called, but graph optimizations may cause new ones to appear. For
9556       // example, the case in pr14333 looks like
9557       //
9558       //  St's chain -> St -> another store -> X
9559       //
9560       // And the only difference from St to the other store is the chain.
9561       // When we change it's chain to be St's chain they become identical,
9562       // get CSEed and the net result is that X is now a use of St.
9563       // Since we know that St is redundant, just iterate.
9564       while (!St->use_empty())
9565         DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
9566       deleteAndRecombine(St);
9567     }
9568
9569     return true;
9570   }
9571
9572   // Below we handle the case of multiple consecutive stores that
9573   // come from multiple consecutive loads. We merge them into a single
9574   // wide load and a single wide store.
9575
9576   // Look for load nodes which are used by the stored values.
9577   SmallVector<MemOpLink, 8> LoadNodes;
9578
9579   // Find acceptable loads. Loads need to have the same chain (token factor),
9580   // must not be zext, volatile, indexed, and they must be consecutive.
9581   BaseIndexOffset LdBasePtr;
9582   for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9583     StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
9584     LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
9585     if (!Ld) break;
9586
9587     // Loads must only have one use.
9588     if (!Ld->hasNUsesOfValue(1, 0))
9589       break;
9590
9591     // Check that the alignment is the same as the stores.
9592     if (Ld->getAlignment() != St->getAlignment())
9593       break;
9594
9595     // The memory operands must not be volatile.
9596     if (Ld->isVolatile() || Ld->isIndexed())
9597       break;
9598
9599     // We do not accept ext loads.
9600     if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
9601       break;
9602
9603     // The stored memory type must be the same.
9604     if (Ld->getMemoryVT() != MemVT)
9605       break;
9606
9607     BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
9608     // If this is not the first ptr that we check.
9609     if (LdBasePtr.Base.getNode()) {
9610       // The base ptr must be the same.
9611       if (!LdPtr.equalBaseIndex(LdBasePtr))
9612         break;
9613     } else {
9614       // Check that all other base pointers are the same as this one.
9615       LdBasePtr = LdPtr;
9616     }
9617
9618     // We found a potential memory operand to merge.
9619     LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
9620   }
9621
9622   if (LoadNodes.size() < 2)
9623     return false;
9624
9625   // If we have load/store pair instructions and we only have two values,
9626   // don't bother.
9627   unsigned RequiredAlignment;
9628   if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
9629       St->getAlignment() >= RequiredAlignment)
9630     return false;
9631
9632   // Scan the memory operations on the chain and find the first non-consecutive
9633   // load memory address. These variables hold the index in the store node
9634   // array.
9635   unsigned LastConsecutiveLoad = 0;
9636   // This variable refers to the size and not index in the array.
9637   unsigned LastLegalVectorType = 0;
9638   unsigned LastLegalIntegerType = 0;
9639   StartAddress = LoadNodes[0].OffsetFromBase;
9640   SDValue FirstChain = LoadNodes[0].MemNode->getChain();
9641   for (unsigned i = 1; i < LoadNodes.size(); ++i) {
9642     // All loads much share the same chain.
9643     if (LoadNodes[i].MemNode->getChain() != FirstChain)
9644       break;
9645
9646     int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
9647     if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9648       break;
9649     LastConsecutiveLoad = i;
9650
9651     // Find a legal type for the vector store.
9652     EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9653     if (TLI.isTypeLegal(StoreTy))
9654       LastLegalVectorType = i + 1;
9655
9656     // Find a legal type for the integer store.
9657     unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9658     StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9659     if (TLI.isTypeLegal(StoreTy))
9660       LastLegalIntegerType = i + 1;
9661     // Or check whether a truncstore and extload is legal.
9662     else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9663              TargetLowering::TypePromoteInteger) {
9664       EVT LegalizedStoredValueTy =
9665         TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
9666       if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
9667           TLI.isLoadExtLegal(ISD::ZEXTLOAD, StoreTy) &&
9668           TLI.isLoadExtLegal(ISD::SEXTLOAD, StoreTy) &&
9669           TLI.isLoadExtLegal(ISD::EXTLOAD, StoreTy))
9670         LastLegalIntegerType = i+1;
9671     }
9672   }
9673
9674   // Only use vector types if the vector type is larger than the integer type.
9675   // If they are the same, use integers.
9676   bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
9677   unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
9678
9679   // We add +1 here because the LastXXX variables refer to location while
9680   // the NumElem refers to array/index size.
9681   unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
9682   NumElem = std::min(LastLegalType, NumElem);
9683
9684   if (NumElem < 2)
9685     return false;
9686
9687   // The earliest Node in the DAG.
9688   unsigned EarliestNodeUsed = 0;
9689   LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9690   for (unsigned i=1; i<NumElem; ++i) {
9691     // Find a chain for the new wide-store operand. Notice that some
9692     // of the store nodes that we found may not be selected for inclusion
9693     // in the wide store. The chain we use needs to be the chain of the
9694     // earliest store node which is *used* and replaced by the wide store.
9695     if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9696       EarliestNodeUsed = i;
9697   }
9698
9699   // Find if it is better to use vectors or integers to load and store
9700   // to memory.
9701   EVT JointMemOpVT;
9702   if (UseVectorTy) {
9703     JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9704   } else {
9705     unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9706     JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9707   }
9708
9709   SDLoc LoadDL(LoadNodes[0].MemNode);
9710   SDLoc StoreDL(StoreNodes[0].MemNode);
9711
9712   LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
9713   SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
9714                                 FirstLoad->getChain(),
9715                                 FirstLoad->getBasePtr(),
9716                                 FirstLoad->getPointerInfo(),
9717                                 false, false, false,
9718                                 FirstLoad->getAlignment());
9719
9720   SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
9721                                   FirstInChain->getBasePtr(),
9722                                   FirstInChain->getPointerInfo(), false, false,
9723                                   FirstInChain->getAlignment());
9724
9725   // Replace one of the loads with the new load.
9726   LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
9727   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
9728                                 SDValue(NewLoad.getNode(), 1));
9729
9730   // Remove the rest of the load chains.
9731   for (unsigned i = 1; i < NumElem ; ++i) {
9732     // Replace all chain users of the old load nodes with the chain of the new
9733     // load node.
9734     LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
9735     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
9736   }
9737
9738   // Replace the first store with the new store.
9739   CombineTo(EarliestOp, NewStore);
9740   // Erase all other stores.
9741   for (unsigned i = 0; i < NumElem ; ++i) {
9742     // Remove all Store nodes.
9743     if (StoreNodes[i].MemNode == EarliestOp)
9744       continue;
9745     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9746     DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
9747     deleteAndRecombine(St);
9748   }
9749
9750   return true;
9751 }
9752
9753 SDValue DAGCombiner::visitSTORE(SDNode *N) {
9754   StoreSDNode *ST  = cast<StoreSDNode>(N);
9755   SDValue Chain = ST->getChain();
9756   SDValue Value = ST->getValue();
9757   SDValue Ptr   = ST->getBasePtr();
9758
9759   // If this is a store of a bit convert, store the input value if the
9760   // resultant store does not need a higher alignment than the original.
9761   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
9762       ST->isUnindexed()) {
9763     unsigned OrigAlign = ST->getAlignment();
9764     EVT SVT = Value.getOperand(0).getValueType();
9765     unsigned Align = TLI.getDataLayout()->
9766       getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
9767     if (Align <= OrigAlign &&
9768         ((!LegalOperations && !ST->isVolatile()) ||
9769          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
9770       return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
9771                           Ptr, ST->getPointerInfo(), ST->isVolatile(),
9772                           ST->isNonTemporal(), OrigAlign,
9773                           ST->getAAInfo());
9774   }
9775
9776   // Turn 'store undef, Ptr' -> nothing.
9777   if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
9778     return Chain;
9779
9780   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
9781   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
9782     // NOTE: If the original store is volatile, this transform must not increase
9783     // the number of stores.  For example, on x86-32 an f64 can be stored in one
9784     // processor operation but an i64 (which is not legal) requires two.  So the
9785     // transform should not be done in this case.
9786     if (Value.getOpcode() != ISD::TargetConstantFP) {
9787       SDValue Tmp;
9788       switch (CFP->getSimpleValueType(0).SimpleTy) {
9789       default: llvm_unreachable("Unknown FP type");
9790       case MVT::f16:    // We don't do this for these yet.
9791       case MVT::f80:
9792       case MVT::f128:
9793       case MVT::ppcf128:
9794         break;
9795       case MVT::f32:
9796         if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
9797             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9798           Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
9799                               bitcastToAPInt().getZExtValue(), MVT::i32);
9800           return DAG.getStore(Chain, SDLoc(N), Tmp,
9801                               Ptr, ST->getMemOperand());
9802         }
9803         break;
9804       case MVT::f64:
9805         if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
9806              !ST->isVolatile()) ||
9807             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
9808           Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
9809                                 getZExtValue(), MVT::i64);
9810           return DAG.getStore(Chain, SDLoc(N), Tmp,
9811                               Ptr, ST->getMemOperand());
9812         }
9813
9814         if (!ST->isVolatile() &&
9815             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9816           // Many FP stores are not made apparent until after legalize, e.g. for
9817           // argument passing.  Since this is so common, custom legalize the
9818           // 64-bit integer store into two 32-bit stores.
9819           uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
9820           SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
9821           SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
9822           if (TLI.isBigEndian()) std::swap(Lo, Hi);
9823
9824           unsigned Alignment = ST->getAlignment();
9825           bool isVolatile = ST->isVolatile();
9826           bool isNonTemporal = ST->isNonTemporal();
9827           AAMDNodes AAInfo = ST->getAAInfo();
9828
9829           SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
9830                                      Ptr, ST->getPointerInfo(),
9831                                      isVolatile, isNonTemporal,
9832                                      ST->getAlignment(), AAInfo);
9833           Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
9834                             DAG.getConstant(4, Ptr.getValueType()));
9835           Alignment = MinAlign(Alignment, 4U);
9836           SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
9837                                      Ptr, ST->getPointerInfo().getWithOffset(4),
9838                                      isVolatile, isNonTemporal,
9839                                      Alignment, AAInfo);
9840           return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
9841                              St0, St1);
9842         }
9843
9844         break;
9845       }
9846     }
9847   }
9848
9849   // Try to infer better alignment information than the store already has.
9850   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
9851     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9852       if (Align > ST->getAlignment())
9853         return DAG.getTruncStore(Chain, SDLoc(N), Value,
9854                                  Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
9855                                  ST->isVolatile(), ST->isNonTemporal(), Align,
9856                                  ST->getAAInfo());
9857     }
9858   }
9859
9860   // Try transforming a pair floating point load / store ops to integer
9861   // load / store ops.
9862   SDValue NewST = TransformFPLoadStorePair(N);
9863   if (NewST.getNode())
9864     return NewST;
9865
9866   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
9867                                                   : DAG.getSubtarget().useAA();
9868 #ifndef NDEBUG
9869   if (CombinerAAOnlyFunc.getNumOccurrences() &&
9870       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9871     UseAA = false;
9872 #endif
9873   if (UseAA && ST->isUnindexed()) {
9874     // Walk up chain skipping non-aliasing memory nodes.
9875     SDValue BetterChain = FindBetterChain(N, Chain);
9876
9877     // If there is a better chain.
9878     if (Chain != BetterChain) {
9879       SDValue ReplStore;
9880
9881       // Replace the chain to avoid dependency.
9882       if (ST->isTruncatingStore()) {
9883         ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
9884                                       ST->getMemoryVT(), ST->getMemOperand());
9885       } else {
9886         ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
9887                                  ST->getMemOperand());
9888       }
9889
9890       // Create token to keep both nodes around.
9891       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9892                                   MVT::Other, Chain, ReplStore);
9893
9894       // Make sure the new and old chains are cleaned up.
9895       AddToWorklist(Token.getNode());
9896
9897       // Don't add users to work list.
9898       return CombineTo(N, Token, false);
9899     }
9900   }
9901
9902   // Try transforming N to an indexed store.
9903   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9904     return SDValue(N, 0);
9905
9906   // FIXME: is there such a thing as a truncating indexed store?
9907   if (ST->isTruncatingStore() && ST->isUnindexed() &&
9908       Value.getValueType().isInteger()) {
9909     // See if we can simplify the input to this truncstore with knowledge that
9910     // only the low bits are being used.  For example:
9911     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
9912     SDValue Shorter =
9913       GetDemandedBits(Value,
9914                       APInt::getLowBitsSet(
9915                         Value.getValueType().getScalarType().getSizeInBits(),
9916                         ST->getMemoryVT().getScalarType().getSizeInBits()));
9917     AddToWorklist(Value.getNode());
9918     if (Shorter.getNode())
9919       return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
9920                                Ptr, ST->getMemoryVT(), ST->getMemOperand());
9921
9922     // Otherwise, see if we can simplify the operation with
9923     // SimplifyDemandedBits, which only works if the value has a single use.
9924     if (SimplifyDemandedBits(Value,
9925                         APInt::getLowBitsSet(
9926                           Value.getValueType().getScalarType().getSizeInBits(),
9927                           ST->getMemoryVT().getScalarType().getSizeInBits())))
9928       return SDValue(N, 0);
9929   }
9930
9931   // If this is a load followed by a store to the same location, then the store
9932   // is dead/noop.
9933   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
9934     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
9935         ST->isUnindexed() && !ST->isVolatile() &&
9936         // There can't be any side effects between the load and store, such as
9937         // a call or store.
9938         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
9939       // The store is dead, remove it.
9940       return Chain;
9941     }
9942   }
9943
9944   // If this is a store followed by a store with the same value to the same
9945   // location, then the store is dead/noop.
9946   if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
9947     if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() &&
9948         ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() &&
9949         ST1->isUnindexed() && !ST1->isVolatile()) {
9950       // The store is dead, remove it.
9951       return Chain;
9952     }
9953   }
9954
9955   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
9956   // truncating store.  We can do this even if this is already a truncstore.
9957   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
9958       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
9959       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
9960                             ST->getMemoryVT())) {
9961     return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
9962                              Ptr, ST->getMemoryVT(), ST->getMemOperand());
9963   }
9964
9965   // Only perform this optimization before the types are legal, because we
9966   // don't want to perform this optimization on every DAGCombine invocation.
9967   if (!LegalTypes) {
9968     bool EverChanged = false;
9969
9970     do {
9971       // There can be multiple store sequences on the same chain.
9972       // Keep trying to merge store sequences until we are unable to do so
9973       // or until we merge the last store on the chain.
9974       bool Changed = MergeConsecutiveStores(ST);
9975       EverChanged |= Changed;
9976       if (!Changed) break;
9977     } while (ST->getOpcode() != ISD::DELETED_NODE);
9978
9979     if (EverChanged)
9980       return SDValue(N, 0);
9981   }
9982
9983   return ReduceLoadOpStoreWidth(N);
9984 }
9985
9986 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
9987   SDValue InVec = N->getOperand(0);
9988   SDValue InVal = N->getOperand(1);
9989   SDValue EltNo = N->getOperand(2);
9990   SDLoc dl(N);
9991
9992   // If the inserted element is an UNDEF, just use the input vector.
9993   if (InVal.getOpcode() == ISD::UNDEF)
9994     return InVec;
9995
9996   EVT VT = InVec.getValueType();
9997
9998   // If we can't generate a legal BUILD_VECTOR, exit
9999   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
10000     return SDValue();
10001
10002   // Check that we know which element is being inserted
10003   if (!isa<ConstantSDNode>(EltNo))
10004     return SDValue();
10005   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
10006
10007   // Canonicalize insert_vector_elt dag nodes.
10008   // Example:
10009   // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
10010   // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
10011   //
10012   // Do this only if the child insert_vector node has one use; also
10013   // do this only if indices are both constants and Idx1 < Idx0.
10014   if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
10015       && isa<ConstantSDNode>(InVec.getOperand(2))) {
10016     unsigned OtherElt =
10017       cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
10018     if (Elt < OtherElt) {
10019       // Swap nodes.
10020       SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
10021                                   InVec.getOperand(0), InVal, EltNo);
10022       AddToWorklist(NewOp.getNode());
10023       return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
10024                          VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
10025     }
10026   }
10027
10028   // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
10029   // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
10030   // vector elements.
10031   SmallVector<SDValue, 8> Ops;
10032   // Do not combine these two vectors if the output vector will not replace
10033   // the input vector.
10034   if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
10035     Ops.append(InVec.getNode()->op_begin(),
10036                InVec.getNode()->op_end());
10037   } else if (InVec.getOpcode() == ISD::UNDEF) {
10038     unsigned NElts = VT.getVectorNumElements();
10039     Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
10040   } else {
10041     return SDValue();
10042   }
10043
10044   // Insert the element
10045   if (Elt < Ops.size()) {
10046     // All the operands of BUILD_VECTOR must have the same type;
10047     // we enforce that here.
10048     EVT OpVT = Ops[0].getValueType();
10049     if (InVal.getValueType() != OpVT)
10050       InVal = OpVT.bitsGT(InVal.getValueType()) ?
10051                 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
10052                 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
10053     Ops[Elt] = InVal;
10054   }
10055
10056   // Return the new vector
10057   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
10058 }
10059
10060 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
10061     SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
10062   EVT ResultVT = EVE->getValueType(0);
10063   EVT VecEltVT = InVecVT.getVectorElementType();
10064   unsigned Align = OriginalLoad->getAlignment();
10065   unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
10066       VecEltVT.getTypeForEVT(*DAG.getContext()));
10067
10068   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
10069     return SDValue();
10070
10071   Align = NewAlign;
10072
10073   SDValue NewPtr = OriginalLoad->getBasePtr();
10074   SDValue Offset;
10075   EVT PtrType = NewPtr.getValueType();
10076   MachinePointerInfo MPI;
10077   if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
10078     int Elt = ConstEltNo->getZExtValue();
10079     unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
10080     if (TLI.isBigEndian())
10081       PtrOff = InVecVT.getSizeInBits() / 8 - PtrOff;
10082     Offset = DAG.getConstant(PtrOff, PtrType);
10083     MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
10084   } else {
10085     Offset = DAG.getNode(
10086         ISD::MUL, SDLoc(EVE), EltNo.getValueType(), EltNo,
10087         DAG.getConstant(VecEltVT.getStoreSize(), EltNo.getValueType()));
10088     if (TLI.isBigEndian())
10089       Offset = DAG.getNode(
10090           ISD::SUB, SDLoc(EVE), EltNo.getValueType(),
10091           DAG.getConstant(InVecVT.getStoreSize(), EltNo.getValueType()), Offset);
10092     MPI = OriginalLoad->getPointerInfo();
10093   }
10094   NewPtr = DAG.getNode(ISD::ADD, SDLoc(EVE), PtrType, NewPtr, Offset);
10095
10096   // The replacement we need to do here is a little tricky: we need to
10097   // replace an extractelement of a load with a load.
10098   // Use ReplaceAllUsesOfValuesWith to do the replacement.
10099   // Note that this replacement assumes that the extractvalue is the only
10100   // use of the load; that's okay because we don't want to perform this
10101   // transformation in other cases anyway.
10102   SDValue Load;
10103   SDValue Chain;
10104   if (ResultVT.bitsGT(VecEltVT)) {
10105     // If the result type of vextract is wider than the load, then issue an
10106     // extending load instead.
10107     ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, VecEltVT)
10108                                    ? ISD::ZEXTLOAD
10109                                    : ISD::EXTLOAD;
10110     Load = DAG.getExtLoad(
10111         ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI,
10112         VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
10113         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
10114     Chain = Load.getValue(1);
10115   } else {
10116     Load = DAG.getLoad(
10117         VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
10118         OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
10119         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
10120     Chain = Load.getValue(1);
10121     if (ResultVT.bitsLT(VecEltVT))
10122       Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
10123     else
10124       Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
10125   }
10126   WorklistRemover DeadNodes(*this);
10127   SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
10128   SDValue To[] = { Load, Chain };
10129   DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
10130   // Since we're explicitly calling ReplaceAllUses, add the new node to the
10131   // worklist explicitly as well.
10132   AddToWorklist(Load.getNode());
10133   AddUsersToWorklist(Load.getNode()); // Add users too
10134   // Make sure to revisit this node to clean it up; it will usually be dead.
10135   AddToWorklist(EVE);
10136   ++OpsNarrowed;
10137   return SDValue(EVE, 0);
10138 }
10139
10140 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
10141   // (vextract (scalar_to_vector val, 0) -> val
10142   SDValue InVec = N->getOperand(0);
10143   EVT VT = InVec.getValueType();
10144   EVT NVT = N->getValueType(0);
10145
10146   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
10147     // Check if the result type doesn't match the inserted element type. A
10148     // SCALAR_TO_VECTOR may truncate the inserted element and the
10149     // EXTRACT_VECTOR_ELT may widen the extracted vector.
10150     SDValue InOp = InVec.getOperand(0);
10151     if (InOp.getValueType() != NVT) {
10152       assert(InOp.getValueType().isInteger() && NVT.isInteger());
10153       return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
10154     }
10155     return InOp;
10156   }
10157
10158   SDValue EltNo = N->getOperand(1);
10159   bool ConstEltNo = isa<ConstantSDNode>(EltNo);
10160
10161   // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
10162   // We only perform this optimization before the op legalization phase because
10163   // we may introduce new vector instructions which are not backed by TD
10164   // patterns. For example on AVX, extracting elements from a wide vector
10165   // without using extract_subvector. However, if we can find an underlying
10166   // scalar value, then we can always use that.
10167   if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
10168       && ConstEltNo) {
10169     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
10170     int NumElem = VT.getVectorNumElements();
10171     ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
10172     // Find the new index to extract from.
10173     int OrigElt = SVOp->getMaskElt(Elt);
10174
10175     // Extracting an undef index is undef.
10176     if (OrigElt == -1)
10177       return DAG.getUNDEF(NVT);
10178
10179     // Select the right vector half to extract from.
10180     SDValue SVInVec;
10181     if (OrigElt < NumElem) {
10182       SVInVec = InVec->getOperand(0);
10183     } else {
10184       SVInVec = InVec->getOperand(1);
10185       OrigElt -= NumElem;
10186     }
10187
10188     if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
10189       SDValue InOp = SVInVec.getOperand(OrigElt);
10190       if (InOp.getValueType() != NVT) {
10191         assert(InOp.getValueType().isInteger() && NVT.isInteger());
10192         InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
10193       }
10194
10195       return InOp;
10196     }
10197
10198     // FIXME: We should handle recursing on other vector shuffles and
10199     // scalar_to_vector here as well.
10200
10201     if (!LegalOperations) {
10202       EVT IndexTy = TLI.getVectorIdxTy();
10203       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
10204                          SVInVec, DAG.getConstant(OrigElt, IndexTy));
10205     }
10206   }
10207
10208   bool BCNumEltsChanged = false;
10209   EVT ExtVT = VT.getVectorElementType();
10210   EVT LVT = ExtVT;
10211
10212   // If the result of load has to be truncated, then it's not necessarily
10213   // profitable.
10214   if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
10215     return SDValue();
10216
10217   if (InVec.getOpcode() == ISD::BITCAST) {
10218     // Don't duplicate a load with other uses.
10219     if (!InVec.hasOneUse())
10220       return SDValue();
10221
10222     EVT BCVT = InVec.getOperand(0).getValueType();
10223     if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
10224       return SDValue();
10225     if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
10226       BCNumEltsChanged = true;
10227     InVec = InVec.getOperand(0);
10228     ExtVT = BCVT.getVectorElementType();
10229   }
10230
10231   // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
10232   if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
10233       ISD::isNormalLoad(InVec.getNode()) &&
10234       !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
10235     SDValue Index = N->getOperand(1);
10236     if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
10237       return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
10238                                                            OrigLoad);
10239   }
10240
10241   // Perform only after legalization to ensure build_vector / vector_shuffle
10242   // optimizations have already been done.
10243   if (!LegalOperations) return SDValue();
10244
10245   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
10246   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
10247   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
10248
10249   if (ConstEltNo) {
10250     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
10251
10252     LoadSDNode *LN0 = nullptr;
10253     const ShuffleVectorSDNode *SVN = nullptr;
10254     if (ISD::isNormalLoad(InVec.getNode())) {
10255       LN0 = cast<LoadSDNode>(InVec);
10256     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
10257                InVec.getOperand(0).getValueType() == ExtVT &&
10258                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
10259       // Don't duplicate a load with other uses.
10260       if (!InVec.hasOneUse())
10261         return SDValue();
10262
10263       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
10264     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
10265       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
10266       // =>
10267       // (load $addr+1*size)
10268
10269       // Don't duplicate a load with other uses.
10270       if (!InVec.hasOneUse())
10271         return SDValue();
10272
10273       // If the bit convert changed the number of elements, it is unsafe
10274       // to examine the mask.
10275       if (BCNumEltsChanged)
10276         return SDValue();
10277
10278       // Select the input vector, guarding against out of range extract vector.
10279       unsigned NumElems = VT.getVectorNumElements();
10280       int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
10281       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
10282
10283       if (InVec.getOpcode() == ISD::BITCAST) {
10284         // Don't duplicate a load with other uses.
10285         if (!InVec.hasOneUse())
10286           return SDValue();
10287
10288         InVec = InVec.getOperand(0);
10289       }
10290       if (ISD::isNormalLoad(InVec.getNode())) {
10291         LN0 = cast<LoadSDNode>(InVec);
10292         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
10293         EltNo = DAG.getConstant(Elt, EltNo.getValueType());
10294       }
10295     }
10296
10297     // Make sure we found a non-volatile load and the extractelement is
10298     // the only use.
10299     if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
10300       return SDValue();
10301
10302     // If Idx was -1 above, Elt is going to be -1, so just return undef.
10303     if (Elt == -1)
10304       return DAG.getUNDEF(LVT);
10305
10306     return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
10307   }
10308
10309   return SDValue();
10310 }
10311
10312 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
10313 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
10314   // We perform this optimization post type-legalization because
10315   // the type-legalizer often scalarizes integer-promoted vectors.
10316   // Performing this optimization before may create bit-casts which
10317   // will be type-legalized to complex code sequences.
10318   // We perform this optimization only before the operation legalizer because we
10319   // may introduce illegal operations.
10320   if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
10321     return SDValue();
10322
10323   unsigned NumInScalars = N->getNumOperands();
10324   SDLoc dl(N);
10325   EVT VT = N->getValueType(0);
10326
10327   // Check to see if this is a BUILD_VECTOR of a bunch of values
10328   // which come from any_extend or zero_extend nodes. If so, we can create
10329   // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
10330   // optimizations. We do not handle sign-extend because we can't fill the sign
10331   // using shuffles.
10332   EVT SourceType = MVT::Other;
10333   bool AllAnyExt = true;
10334
10335   for (unsigned i = 0; i != NumInScalars; ++i) {
10336     SDValue In = N->getOperand(i);
10337     // Ignore undef inputs.
10338     if (In.getOpcode() == ISD::UNDEF) continue;
10339
10340     bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
10341     bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
10342
10343     // Abort if the element is not an extension.
10344     if (!ZeroExt && !AnyExt) {
10345       SourceType = MVT::Other;
10346       break;
10347     }
10348
10349     // The input is a ZeroExt or AnyExt. Check the original type.
10350     EVT InTy = In.getOperand(0).getValueType();
10351
10352     // Check that all of the widened source types are the same.
10353     if (SourceType == MVT::Other)
10354       // First time.
10355       SourceType = InTy;
10356     else if (InTy != SourceType) {
10357       // Multiple income types. Abort.
10358       SourceType = MVT::Other;
10359       break;
10360     }
10361
10362     // Check if all of the extends are ANY_EXTENDs.
10363     AllAnyExt &= AnyExt;
10364   }
10365
10366   // In order to have valid types, all of the inputs must be extended from the
10367   // same source type and all of the inputs must be any or zero extend.
10368   // Scalar sizes must be a power of two.
10369   EVT OutScalarTy = VT.getScalarType();
10370   bool ValidTypes = SourceType != MVT::Other &&
10371                  isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
10372                  isPowerOf2_32(SourceType.getSizeInBits());
10373
10374   // Create a new simpler BUILD_VECTOR sequence which other optimizations can
10375   // turn into a single shuffle instruction.
10376   if (!ValidTypes)
10377     return SDValue();
10378
10379   bool isLE = TLI.isLittleEndian();
10380   unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
10381   assert(ElemRatio > 1 && "Invalid element size ratio");
10382   SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
10383                                DAG.getConstant(0, SourceType);
10384
10385   unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
10386   SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
10387
10388   // Populate the new build_vector
10389   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10390     SDValue Cast = N->getOperand(i);
10391     assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
10392             Cast.getOpcode() == ISD::ZERO_EXTEND ||
10393             Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
10394     SDValue In;
10395     if (Cast.getOpcode() == ISD::UNDEF)
10396       In = DAG.getUNDEF(SourceType);
10397     else
10398       In = Cast->getOperand(0);
10399     unsigned Index = isLE ? (i * ElemRatio) :
10400                             (i * ElemRatio + (ElemRatio - 1));
10401
10402     assert(Index < Ops.size() && "Invalid index");
10403     Ops[Index] = In;
10404   }
10405
10406   // The type of the new BUILD_VECTOR node.
10407   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
10408   assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
10409          "Invalid vector size");
10410   // Check if the new vector type is legal.
10411   if (!isTypeLegal(VecVT)) return SDValue();
10412
10413   // Make the new BUILD_VECTOR.
10414   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
10415
10416   // The new BUILD_VECTOR node has the potential to be further optimized.
10417   AddToWorklist(BV.getNode());
10418   // Bitcast to the desired type.
10419   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
10420 }
10421
10422 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
10423   EVT VT = N->getValueType(0);
10424
10425   unsigned NumInScalars = N->getNumOperands();
10426   SDLoc dl(N);
10427
10428   EVT SrcVT = MVT::Other;
10429   unsigned Opcode = ISD::DELETED_NODE;
10430   unsigned NumDefs = 0;
10431
10432   for (unsigned i = 0; i != NumInScalars; ++i) {
10433     SDValue In = N->getOperand(i);
10434     unsigned Opc = In.getOpcode();
10435
10436     if (Opc == ISD::UNDEF)
10437       continue;
10438
10439     // If all scalar values are floats and converted from integers.
10440     if (Opcode == ISD::DELETED_NODE &&
10441         (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
10442       Opcode = Opc;
10443     }
10444
10445     if (Opc != Opcode)
10446       return SDValue();
10447
10448     EVT InVT = In.getOperand(0).getValueType();
10449
10450     // If all scalar values are typed differently, bail out. It's chosen to
10451     // simplify BUILD_VECTOR of integer types.
10452     if (SrcVT == MVT::Other)
10453       SrcVT = InVT;
10454     if (SrcVT != InVT)
10455       return SDValue();
10456     NumDefs++;
10457   }
10458
10459   // If the vector has just one element defined, it's not worth to fold it into
10460   // a vectorized one.
10461   if (NumDefs < 2)
10462     return SDValue();
10463
10464   assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
10465          && "Should only handle conversion from integer to float.");
10466   assert(SrcVT != MVT::Other && "Cannot determine source type!");
10467
10468   EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
10469
10470   if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
10471     return SDValue();
10472
10473   SmallVector<SDValue, 8> Opnds;
10474   for (unsigned i = 0; i != NumInScalars; ++i) {
10475     SDValue In = N->getOperand(i);
10476
10477     if (In.getOpcode() == ISD::UNDEF)
10478       Opnds.push_back(DAG.getUNDEF(SrcVT));
10479     else
10480       Opnds.push_back(In.getOperand(0));
10481   }
10482   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
10483   AddToWorklist(BV.getNode());
10484
10485   return DAG.getNode(Opcode, dl, VT, BV);
10486 }
10487
10488 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
10489   unsigned NumInScalars = N->getNumOperands();
10490   SDLoc dl(N);
10491   EVT VT = N->getValueType(0);
10492
10493   // A vector built entirely of undefs is undef.
10494   if (ISD::allOperandsUndef(N))
10495     return DAG.getUNDEF(VT);
10496
10497   SDValue V = reduceBuildVecExtToExtBuildVec(N);
10498   if (V.getNode())
10499     return V;
10500
10501   V = reduceBuildVecConvertToConvertBuildVec(N);
10502   if (V.getNode())
10503     return V;
10504
10505   // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
10506   // operations.  If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
10507   // at most two distinct vectors, turn this into a shuffle node.
10508
10509   // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
10510   if (!isTypeLegal(VT))
10511     return SDValue();
10512
10513   // May only combine to shuffle after legalize if shuffle is legal.
10514   if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
10515     return SDValue();
10516
10517   SDValue VecIn1, VecIn2;
10518   for (unsigned i = 0; i != NumInScalars; ++i) {
10519     // Ignore undef inputs.
10520     if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
10521
10522     // If this input is something other than a EXTRACT_VECTOR_ELT with a
10523     // constant index, bail out.
10524     if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10525         !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
10526       VecIn1 = VecIn2 = SDValue(nullptr, 0);
10527       break;
10528     }
10529
10530     // We allow up to two distinct input vectors.
10531     SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
10532     if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
10533       continue;
10534
10535     if (!VecIn1.getNode()) {
10536       VecIn1 = ExtractedFromVec;
10537     } else if (!VecIn2.getNode()) {
10538       VecIn2 = ExtractedFromVec;
10539     } else {
10540       // Too many inputs.
10541       VecIn1 = VecIn2 = SDValue(nullptr, 0);
10542       break;
10543     }
10544   }
10545
10546   // If everything is good, we can make a shuffle operation.
10547   if (VecIn1.getNode()) {
10548     SmallVector<int, 8> Mask;
10549     for (unsigned i = 0; i != NumInScalars; ++i) {
10550       if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
10551         Mask.push_back(-1);
10552         continue;
10553       }
10554
10555       // If extracting from the first vector, just use the index directly.
10556       SDValue Extract = N->getOperand(i);
10557       SDValue ExtVal = Extract.getOperand(1);
10558       if (Extract.getOperand(0) == VecIn1) {
10559         unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10560         if (ExtIndex > VT.getVectorNumElements())
10561           return SDValue();
10562
10563         Mask.push_back(ExtIndex);
10564         continue;
10565       }
10566
10567       // Otherwise, use InIdx + VecSize
10568       unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10569       Mask.push_back(Idx+NumInScalars);
10570     }
10571
10572     // We can't generate a shuffle node with mismatched input and output types.
10573     // Attempt to transform a single input vector to the correct type.
10574     if ((VT != VecIn1.getValueType())) {
10575       // We don't support shuffeling between TWO values of different types.
10576       if (VecIn2.getNode())
10577         return SDValue();
10578
10579       // We only support widening of vectors which are half the size of the
10580       // output registers. For example XMM->YMM widening on X86 with AVX.
10581       if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits())
10582         return SDValue();
10583
10584       // If the input vector type has a different base type to the output
10585       // vector type, bail out.
10586       if (VecIn1.getValueType().getVectorElementType() !=
10587           VT.getVectorElementType())
10588         return SDValue();
10589
10590       // Widen the input vector by adding undef values.
10591       VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10592                            VecIn1, DAG.getUNDEF(VecIn1.getValueType()));
10593     }
10594
10595     // If VecIn2 is unused then change it to undef.
10596     VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
10597
10598     // Check that we were able to transform all incoming values to the same
10599     // type.
10600     if (VecIn2.getValueType() != VecIn1.getValueType() ||
10601         VecIn1.getValueType() != VT)
10602           return SDValue();
10603
10604     // Return the new VECTOR_SHUFFLE node.
10605     SDValue Ops[2];
10606     Ops[0] = VecIn1;
10607     Ops[1] = VecIn2;
10608     return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
10609   }
10610
10611   return SDValue();
10612 }
10613
10614 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
10615   // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
10616   // EXTRACT_SUBVECTOR operations.  If so, and if the EXTRACT_SUBVECTOR vector
10617   // inputs come from at most two distinct vectors, turn this into a shuffle
10618   // node.
10619
10620   // If we only have one input vector, we don't need to do any concatenation.
10621   if (N->getNumOperands() == 1)
10622     return N->getOperand(0);
10623
10624   // Check if all of the operands are undefs.
10625   EVT VT = N->getValueType(0);
10626   if (ISD::allOperandsUndef(N))
10627     return DAG.getUNDEF(VT);
10628
10629   // Optimize concat_vectors where one of the vectors is undef.
10630   if (N->getNumOperands() == 2 &&
10631       N->getOperand(1)->getOpcode() == ISD::UNDEF) {
10632     SDValue In = N->getOperand(0);
10633     assert(In.getValueType().isVector() && "Must concat vectors");
10634
10635     // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
10636     if (In->getOpcode() == ISD::BITCAST &&
10637         !In->getOperand(0)->getValueType(0).isVector()) {
10638       SDValue Scalar = In->getOperand(0);
10639       EVT SclTy = Scalar->getValueType(0);
10640
10641       if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
10642         return SDValue();
10643
10644       EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
10645                                  VT.getSizeInBits() / SclTy.getSizeInBits());
10646       if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
10647         return SDValue();
10648
10649       SDLoc dl = SDLoc(N);
10650       SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
10651       return DAG.getNode(ISD::BITCAST, dl, VT, Res);
10652     }
10653   }
10654
10655   // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
10656   // -> (BUILD_VECTOR A, B, ..., C, D, ...)
10657   if (N->getNumOperands() == 2 &&
10658       N->getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
10659       N->getOperand(1).getOpcode() == ISD::BUILD_VECTOR) {
10660     EVT VT = N->getValueType(0);
10661     SDValue N0 = N->getOperand(0);
10662     SDValue N1 = N->getOperand(1);
10663     SmallVector<SDValue, 8> Opnds;
10664     unsigned BuildVecNumElts =  N0.getNumOperands();
10665
10666     EVT SclTy0 = N0.getOperand(0)->getValueType(0);
10667     EVT SclTy1 = N1.getOperand(0)->getValueType(0);
10668     if (SclTy0.isFloatingPoint()) {
10669       for (unsigned i = 0; i != BuildVecNumElts; ++i)
10670         Opnds.push_back(N0.getOperand(i));
10671       for (unsigned i = 0; i != BuildVecNumElts; ++i)
10672         Opnds.push_back(N1.getOperand(i));
10673     } else {
10674       // If BUILD_VECTOR are from built from integer, they may have different
10675       // operand types. Get the smaller type and truncate all operands to it.
10676       EVT MinTy = SclTy0.bitsLE(SclTy1) ? SclTy0 : SclTy1;
10677       for (unsigned i = 0; i != BuildVecNumElts; ++i)
10678         Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy,
10679                         N0.getOperand(i)));
10680       for (unsigned i = 0; i != BuildVecNumElts; ++i)
10681         Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy,
10682                         N1.getOperand(i)));
10683     }
10684
10685     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
10686   }
10687
10688   // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
10689   // nodes often generate nop CONCAT_VECTOR nodes.
10690   // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
10691   // place the incoming vectors at the exact same location.
10692   SDValue SingleSource = SDValue();
10693   unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
10694
10695   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10696     SDValue Op = N->getOperand(i);
10697
10698     if (Op.getOpcode() == ISD::UNDEF)
10699       continue;
10700
10701     // Check if this is the identity extract:
10702     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
10703       return SDValue();
10704
10705     // Find the single incoming vector for the extract_subvector.
10706     if (SingleSource.getNode()) {
10707       if (Op.getOperand(0) != SingleSource)
10708         return SDValue();
10709     } else {
10710       SingleSource = Op.getOperand(0);
10711
10712       // Check the source type is the same as the type of the result.
10713       // If not, this concat may extend the vector, so we can not
10714       // optimize it away.
10715       if (SingleSource.getValueType() != N->getValueType(0))
10716         return SDValue();
10717     }
10718
10719     unsigned IdentityIndex = i * PartNumElem;
10720     ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10721     // The extract index must be constant.
10722     if (!CS)
10723       return SDValue();
10724
10725     // Check that we are reading from the identity index.
10726     if (CS->getZExtValue() != IdentityIndex)
10727       return SDValue();
10728   }
10729
10730   if (SingleSource.getNode())
10731     return SingleSource;
10732
10733   return SDValue();
10734 }
10735
10736 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
10737   EVT NVT = N->getValueType(0);
10738   SDValue V = N->getOperand(0);
10739
10740   if (V->getOpcode() == ISD::CONCAT_VECTORS) {
10741     // Combine:
10742     //    (extract_subvec (concat V1, V2, ...), i)
10743     // Into:
10744     //    Vi if possible
10745     // Only operand 0 is checked as 'concat' assumes all inputs of the same
10746     // type.
10747     if (V->getOperand(0).getValueType() != NVT)
10748       return SDValue();
10749     unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10750     unsigned NumElems = NVT.getVectorNumElements();
10751     assert((Idx % NumElems) == 0 &&
10752            "IDX in concat is not a multiple of the result vector length.");
10753     return V->getOperand(Idx / NumElems);
10754   }
10755
10756   // Skip bitcasting
10757   if (V->getOpcode() == ISD::BITCAST)
10758     V = V.getOperand(0);
10759
10760   if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
10761     SDLoc dl(N);
10762     // Handle only simple case where vector being inserted and vector
10763     // being extracted are of same type, and are half size of larger vectors.
10764     EVT BigVT = V->getOperand(0).getValueType();
10765     EVT SmallVT = V->getOperand(1).getValueType();
10766     if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
10767       return SDValue();
10768
10769     // Only handle cases where both indexes are constants with the same type.
10770     ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10771     ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
10772
10773     if (InsIdx && ExtIdx &&
10774         InsIdx->getValueType(0).getSizeInBits() <= 64 &&
10775         ExtIdx->getValueType(0).getSizeInBits() <= 64) {
10776       // Combine:
10777       //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
10778       // Into:
10779       //    indices are equal or bit offsets are equal => V1
10780       //    otherwise => (extract_subvec V1, ExtIdx)
10781       if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
10782           ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
10783         return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
10784       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
10785                          DAG.getNode(ISD::BITCAST, dl,
10786                                      N->getOperand(0).getValueType(),
10787                                      V->getOperand(0)), N->getOperand(1));
10788     }
10789   }
10790
10791   return SDValue();
10792 }
10793
10794 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
10795                                                  SDValue V, SelectionDAG &DAG) {
10796   SDLoc DL(V);
10797   EVT VT = V.getValueType();
10798
10799   switch (V.getOpcode()) {
10800   default:
10801     return V;
10802
10803   case ISD::CONCAT_VECTORS: {
10804     EVT OpVT = V->getOperand(0).getValueType();
10805     int OpSize = OpVT.getVectorNumElements();
10806     SmallBitVector OpUsedElements(OpSize, false);
10807     bool FoundSimplification = false;
10808     SmallVector<SDValue, 4> NewOps;
10809     NewOps.reserve(V->getNumOperands());
10810     for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
10811       SDValue Op = V->getOperand(i);
10812       bool OpUsed = false;
10813       for (int j = 0; j < OpSize; ++j)
10814         if (UsedElements[i * OpSize + j]) {
10815           OpUsedElements[j] = true;
10816           OpUsed = true;
10817         }
10818       NewOps.push_back(
10819           OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
10820                  : DAG.getUNDEF(OpVT));
10821       FoundSimplification |= Op == NewOps.back();
10822       OpUsedElements.reset();
10823     }
10824     if (FoundSimplification)
10825       V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
10826     return V;
10827   }
10828
10829   case ISD::INSERT_SUBVECTOR: {
10830     SDValue BaseV = V->getOperand(0);
10831     SDValue SubV = V->getOperand(1);
10832     auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
10833     if (!IdxN)
10834       return V;
10835
10836     int SubSize = SubV.getValueType().getVectorNumElements();
10837     int Idx = IdxN->getZExtValue();
10838     bool SubVectorUsed = false;
10839     SmallBitVector SubUsedElements(SubSize, false);
10840     for (int i = 0; i < SubSize; ++i)
10841       if (UsedElements[i + Idx]) {
10842         SubVectorUsed = true;
10843         SubUsedElements[i] = true;
10844         UsedElements[i + Idx] = false;
10845       }
10846
10847     // Now recurse on both the base and sub vectors.
10848     SDValue SimplifiedSubV =
10849         SubVectorUsed
10850             ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
10851             : DAG.getUNDEF(SubV.getValueType());
10852     SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
10853     if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
10854       V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
10855                       SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
10856     return V;
10857   }
10858   }
10859 }
10860
10861 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
10862                                        SDValue N1, SelectionDAG &DAG) {
10863   EVT VT = SVN->getValueType(0);
10864   int NumElts = VT.getVectorNumElements();
10865   SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
10866   for (int M : SVN->getMask())
10867     if (M >= 0 && M < NumElts)
10868       N0UsedElements[M] = true;
10869     else if (M >= NumElts)
10870       N1UsedElements[M - NumElts] = true;
10871
10872   SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
10873   SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
10874   if (S0 == N0 && S1 == N1)
10875     return SDValue();
10876
10877   return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
10878 }
10879
10880 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat.
10881 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
10882   EVT VT = N->getValueType(0);
10883   unsigned NumElts = VT.getVectorNumElements();
10884
10885   SDValue N0 = N->getOperand(0);
10886   SDValue N1 = N->getOperand(1);
10887   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10888
10889   SmallVector<SDValue, 4> Ops;
10890   EVT ConcatVT = N0.getOperand(0).getValueType();
10891   unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
10892   unsigned NumConcats = NumElts / NumElemsPerConcat;
10893
10894   // Look at every vector that's inserted. We're looking for exact
10895   // subvector-sized copies from a concatenated vector
10896   for (unsigned I = 0; I != NumConcats; ++I) {
10897     // Make sure we're dealing with a copy.
10898     unsigned Begin = I * NumElemsPerConcat;
10899     bool AllUndef = true, NoUndef = true;
10900     for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
10901       if (SVN->getMaskElt(J) >= 0)
10902         AllUndef = false;
10903       else
10904         NoUndef = false;
10905     }
10906
10907     if (NoUndef) {
10908       if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
10909         return SDValue();
10910
10911       for (unsigned J = 1; J != NumElemsPerConcat; ++J)
10912         if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
10913           return SDValue();
10914
10915       unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
10916       if (FirstElt < N0.getNumOperands())
10917         Ops.push_back(N0.getOperand(FirstElt));
10918       else
10919         Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
10920
10921     } else if (AllUndef) {
10922       Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
10923     } else { // Mixed with general masks and undefs, can't do optimization.
10924       return SDValue();
10925     }
10926   }
10927
10928   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
10929 }
10930
10931 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
10932   EVT VT = N->getValueType(0);
10933   unsigned NumElts = VT.getVectorNumElements();
10934
10935   SDValue N0 = N->getOperand(0);
10936   SDValue N1 = N->getOperand(1);
10937
10938   assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
10939
10940   // Canonicalize shuffle undef, undef -> undef
10941   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
10942     return DAG.getUNDEF(VT);
10943
10944   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10945
10946   // Canonicalize shuffle v, v -> v, undef
10947   if (N0 == N1) {
10948     SmallVector<int, 8> NewMask;
10949     for (unsigned i = 0; i != NumElts; ++i) {
10950       int Idx = SVN->getMaskElt(i);
10951       if (Idx >= (int)NumElts) Idx -= NumElts;
10952       NewMask.push_back(Idx);
10953     }
10954     return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
10955                                 &NewMask[0]);
10956   }
10957
10958   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
10959   if (N0.getOpcode() == ISD::UNDEF) {
10960     SmallVector<int, 8> NewMask;
10961     for (unsigned i = 0; i != NumElts; ++i) {
10962       int Idx = SVN->getMaskElt(i);
10963       if (Idx >= 0) {
10964         if (Idx >= (int)NumElts)
10965           Idx -= NumElts;
10966         else
10967           Idx = -1; // remove reference to lhs
10968       }
10969       NewMask.push_back(Idx);
10970     }
10971     return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
10972                                 &NewMask[0]);
10973   }
10974
10975   // Remove references to rhs if it is undef
10976   if (N1.getOpcode() == ISD::UNDEF) {
10977     bool Changed = false;
10978     SmallVector<int, 8> NewMask;
10979     for (unsigned i = 0; i != NumElts; ++i) {
10980       int Idx = SVN->getMaskElt(i);
10981       if (Idx >= (int)NumElts) {
10982         Idx = -1;
10983         Changed = true;
10984       }
10985       NewMask.push_back(Idx);
10986     }
10987     if (Changed)
10988       return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
10989   }
10990
10991   // If it is a splat, check if the argument vector is another splat or a
10992   // build_vector with all scalar elements the same.
10993   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
10994     SDNode *V = N0.getNode();
10995
10996     // If this is a bit convert that changes the element type of the vector but
10997     // not the number of vector elements, look through it.  Be careful not to
10998     // look though conversions that change things like v4f32 to v2f64.
10999     if (V->getOpcode() == ISD::BITCAST) {
11000       SDValue ConvInput = V->getOperand(0);
11001       if (ConvInput.getValueType().isVector() &&
11002           ConvInput.getValueType().getVectorNumElements() == NumElts)
11003         V = ConvInput.getNode();
11004     }
11005
11006     if (V->getOpcode() == ISD::BUILD_VECTOR) {
11007       assert(V->getNumOperands() == NumElts &&
11008              "BUILD_VECTOR has wrong number of operands");
11009       SDValue Base;
11010       bool AllSame = true;
11011       for (unsigned i = 0; i != NumElts; ++i) {
11012         if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
11013           Base = V->getOperand(i);
11014           break;
11015         }
11016       }
11017       // Splat of <u, u, u, u>, return <u, u, u, u>
11018       if (!Base.getNode())
11019         return N0;
11020       for (unsigned i = 0; i != NumElts; ++i) {
11021         if (V->getOperand(i) != Base) {
11022           AllSame = false;
11023           break;
11024         }
11025       }
11026       // Splat of <x, x, x, x>, return <x, x, x, x>
11027       if (AllSame)
11028         return N0;
11029     }
11030   }
11031
11032   // There are various patterns used to build up a vector from smaller vectors,
11033   // subvectors, or elements. Scan chains of these and replace unused insertions
11034   // or components with undef.
11035   if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
11036     return S;
11037
11038   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
11039       Level < AfterLegalizeVectorOps &&
11040       (N1.getOpcode() == ISD::UNDEF ||
11041       (N1.getOpcode() == ISD::CONCAT_VECTORS &&
11042        N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
11043     SDValue V = partitionShuffleOfConcats(N, DAG);
11044
11045     if (V.getNode())
11046       return V;
11047   }
11048
11049   // If this shuffle node is simply a swizzle of another shuffle node,
11050   // then try to simplify it.
11051   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
11052       N1.getOpcode() == ISD::UNDEF) {
11053
11054     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
11055
11056     // The incoming shuffle must be of the same type as the result of the
11057     // current shuffle.
11058     assert(OtherSV->getOperand(0).getValueType() == VT &&
11059            "Shuffle types don't match");
11060
11061     SmallVector<int, 4> Mask;
11062     // Compute the combined shuffle mask.
11063     for (unsigned i = 0; i != NumElts; ++i) {
11064       int Idx = SVN->getMaskElt(i);
11065       assert(Idx < (int)NumElts && "Index references undef operand");
11066       // Next, this index comes from the first value, which is the incoming
11067       // shuffle. Adopt the incoming index.
11068       if (Idx >= 0)
11069         Idx = OtherSV->getMaskElt(Idx);
11070       Mask.push_back(Idx);
11071     }
11072
11073     // Check if all indices in Mask are Undef. In case, propagate Undef.
11074     bool isUndefMask = true;
11075     for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
11076       isUndefMask &= Mask[i] < 0;
11077
11078     if (isUndefMask)
11079       return DAG.getUNDEF(VT);
11080
11081     bool CommuteOperands = false;
11082     if (N0.getOperand(1).getOpcode() != ISD::UNDEF) {
11083       // To be valid, the combine shuffle mask should only reference elements
11084       // from one of the two vectors in input to the inner shufflevector.
11085       bool IsValidMask = true;
11086       for (unsigned i = 0; i != NumElts && IsValidMask; ++i)
11087         // See if the combined mask only reference undefs or elements coming
11088         // from the first shufflevector operand.
11089         IsValidMask = Mask[i] < 0 || (unsigned)Mask[i] < NumElts;
11090
11091       if (!IsValidMask) {
11092         IsValidMask = true;
11093         for (unsigned i = 0; i != NumElts && IsValidMask; ++i)
11094           // Check that all the elements come from the second shuffle operand.
11095           IsValidMask = Mask[i] < 0 || (unsigned)Mask[i] >= NumElts;
11096         CommuteOperands = IsValidMask;
11097       }
11098
11099       // Early exit if the combined shuffle mask is not valid.
11100       if (!IsValidMask)
11101         return SDValue();
11102     }
11103
11104     // See if this pair of shuffles can be safely folded according to either
11105     // of the following rules:
11106     //   shuffle(shuffle(x, y), undef) -> x
11107     //   shuffle(shuffle(x, undef), undef) -> x
11108     //   shuffle(shuffle(x, y), undef) -> y
11109     bool IsIdentityMask = true;
11110     unsigned BaseMaskIndex = CommuteOperands ? NumElts : 0;
11111     for (unsigned i = 0; i != NumElts && IsIdentityMask; ++i) {
11112       // Skip Undefs.
11113       if (Mask[i] < 0)
11114         continue;
11115
11116       // The combined shuffle must map each index to itself.
11117       IsIdentityMask = (unsigned)Mask[i] == i + BaseMaskIndex;
11118     }
11119
11120     if (IsIdentityMask) {
11121       if (CommuteOperands)
11122         // optimize shuffle(shuffle(x, y), undef) -> y.
11123         return OtherSV->getOperand(1);
11124
11125       // optimize shuffle(shuffle(x, undef), undef) -> x
11126       // optimize shuffle(shuffle(x, y), undef) -> x
11127       return OtherSV->getOperand(0);
11128     }
11129
11130     // It may still be beneficial to combine the two shuffles if the
11131     // resulting shuffle is legal.
11132     if (TLI.isTypeLegal(VT)) {
11133       if (!CommuteOperands) {
11134         if (TLI.isShuffleMaskLegal(Mask, VT))
11135           // shuffle(shuffle(x, undef, M1), undef, M2) -> shuffle(x, undef, M3).
11136           // shuffle(shuffle(x, y, M1), undef, M2) -> shuffle(x, undef, M3)
11137           return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0), N1,
11138                                       &Mask[0]);
11139       } else {
11140         // Compute the commuted shuffle mask.
11141         for (unsigned i = 0; i != NumElts; ++i) {
11142           int idx = Mask[i];
11143           if (idx < 0)
11144             continue;
11145           else if (idx < (int)NumElts)
11146             Mask[i] = idx + NumElts;
11147           else
11148             Mask[i] = idx - NumElts;
11149         }
11150
11151         if (TLI.isShuffleMaskLegal(Mask, VT))
11152           //   shuffle(shuffle(x, y, M1), undef, M2) -> shuffle(y, undef, M3)
11153           return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(1), N1,
11154                                       &Mask[0]);
11155       }
11156     }
11157   }
11158
11159   // Canonicalize shuffles according to rules:
11160   //  shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
11161   //  shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
11162   //  shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
11163   if (N1.getOpcode() == ISD::VECTOR_SHUFFLE && N0.getOpcode() != ISD::UNDEF &&
11164       N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
11165       TLI.isTypeLegal(VT)) {
11166     // The incoming shuffle must be of the same type as the result of the
11167     // current shuffle.
11168     assert(N1->getOperand(0).getValueType() == VT &&
11169            "Shuffle types don't match");
11170
11171     SDValue SV0 = N1->getOperand(0);
11172     SDValue SV1 = N1->getOperand(1);
11173     bool HasSameOp0 = N0 == SV0;
11174     bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
11175     if (HasSameOp0 || IsSV1Undef || N0 == SV1)
11176       // Commute the operands of this shuffle so that next rule
11177       // will trigger.
11178       return DAG.getCommutedVectorShuffle(*SVN);
11179   }
11180
11181   // Try to fold according to rules:
11182   //   shuffle(shuffle(A, B, M0), B, M1) -> shuffle(A, B, M2)
11183   //   shuffle(shuffle(A, B, M0), A, M1) -> shuffle(A, B, M2)
11184   //   shuffle(shuffle(A, Undef, M0), B, M1) -> shuffle(A, B, M2)
11185   //   shuffle(shuffle(A, Undef, M0), A, M1) -> shuffle(A, Undef, M2)
11186   // Don't try to fold shuffles with illegal type.
11187   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
11188       N1.getOpcode() != ISD::UNDEF && TLI.isTypeLegal(VT)) {
11189     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
11190
11191     // The incoming shuffle must be of the same type as the result of the
11192     // current shuffle.
11193     assert(OtherSV->getOperand(0).getValueType() == VT &&
11194            "Shuffle types don't match");
11195
11196     SDValue SV0 = OtherSV->getOperand(0);
11197     SDValue SV1 = OtherSV->getOperand(1);
11198     bool HasSameOp0 = N1 == SV0;
11199     bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
11200     if (!HasSameOp0 && !IsSV1Undef && N1 != SV1)
11201       // Early exit.
11202       return SDValue();
11203
11204     SmallVector<int, 4> Mask;
11205     // Compute the combined shuffle mask for a shuffle with SV0 as the first
11206     // operand, and SV1 as the second operand.
11207     for (unsigned i = 0; i != NumElts; ++i) {
11208       int Idx = SVN->getMaskElt(i);
11209       if (Idx < 0) {
11210         // Propagate Undef.
11211         Mask.push_back(Idx);
11212         continue;
11213       }
11214
11215       if (Idx < (int)NumElts) {
11216         Idx = OtherSV->getMaskElt(Idx);
11217         if (IsSV1Undef && Idx >= (int) NumElts)
11218           Idx = -1;  // Propagate Undef.
11219       } else
11220         Idx = HasSameOp0 ? Idx - NumElts : Idx;
11221
11222       Mask.push_back(Idx);
11223     }
11224
11225     // Check if all indices in Mask are Undef. In case, propagate Undef.
11226     bool isUndefMask = true;
11227     for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
11228       isUndefMask &= Mask[i] < 0;
11229
11230     if (isUndefMask)
11231       return DAG.getUNDEF(VT);
11232
11233     // Avoid introducing shuffles with illegal mask.
11234     if (TLI.isShuffleMaskLegal(Mask, VT)) {
11235       if (IsSV1Undef)
11236         //   shuffle(shuffle(A, Undef, M0), B, M1) -> shuffle(A, B, M2)
11237         //   shuffle(shuffle(A, Undef, M0), A, M1) -> shuffle(A, Undef, M2)
11238         return DAG.getVectorShuffle(VT, SDLoc(N), SV0, N1, &Mask[0]);
11239       return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
11240     }
11241   }
11242
11243   return SDValue();
11244 }
11245
11246 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
11247   SDValue N0 = N->getOperand(0);
11248   SDValue N2 = N->getOperand(2);
11249
11250   // If the input vector is a concatenation, and the insert replaces
11251   // one of the halves, we can optimize into a single concat_vectors.
11252   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
11253       N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
11254     APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
11255     EVT VT = N->getValueType(0);
11256
11257     // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
11258     // (concat_vectors Z, Y)
11259     if (InsIdx == 0)
11260       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
11261                          N->getOperand(1), N0.getOperand(1));
11262
11263     // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
11264     // (concat_vectors X, Z)
11265     if (InsIdx == VT.getVectorNumElements()/2)
11266       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
11267                          N0.getOperand(0), N->getOperand(1));
11268   }
11269
11270   return SDValue();
11271 }
11272
11273 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
11274 /// with the destination vector and a zero vector.
11275 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
11276 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
11277 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
11278   EVT VT = N->getValueType(0);
11279   SDLoc dl(N);
11280   SDValue LHS = N->getOperand(0);
11281   SDValue RHS = N->getOperand(1);
11282   if (N->getOpcode() == ISD::AND) {
11283     if (RHS.getOpcode() == ISD::BITCAST)
11284       RHS = RHS.getOperand(0);
11285     if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
11286       SmallVector<int, 8> Indices;
11287       unsigned NumElts = RHS.getNumOperands();
11288       for (unsigned i = 0; i != NumElts; ++i) {
11289         SDValue Elt = RHS.getOperand(i);
11290         if (!isa<ConstantSDNode>(Elt))
11291           return SDValue();
11292
11293         if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
11294           Indices.push_back(i);
11295         else if (cast<ConstantSDNode>(Elt)->isNullValue())
11296           Indices.push_back(NumElts);
11297         else
11298           return SDValue();
11299       }
11300
11301       // Let's see if the target supports this vector_shuffle.
11302       EVT RVT = RHS.getValueType();
11303       if (!TLI.isVectorClearMaskLegal(Indices, RVT))
11304         return SDValue();
11305
11306       // Return the new VECTOR_SHUFFLE node.
11307       EVT EltVT = RVT.getVectorElementType();
11308       SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
11309                                      DAG.getConstant(0, EltVT));
11310       SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), RVT, ZeroOps);
11311       LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
11312       SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
11313       return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
11314     }
11315   }
11316
11317   return SDValue();
11318 }
11319
11320 /// Visit a binary vector operation, like ADD.
11321 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
11322   assert(N->getValueType(0).isVector() &&
11323          "SimplifyVBinOp only works on vectors!");
11324
11325   SDValue LHS = N->getOperand(0);
11326   SDValue RHS = N->getOperand(1);
11327   SDValue Shuffle = XformToShuffleWithZero(N);
11328   if (Shuffle.getNode()) return Shuffle;
11329
11330   // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
11331   // this operation.
11332   if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
11333       RHS.getOpcode() == ISD::BUILD_VECTOR) {
11334     // Check if both vectors are constants. If not bail out.
11335     if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
11336           cast<BuildVectorSDNode>(RHS)->isConstant()))
11337       return SDValue();
11338
11339     SmallVector<SDValue, 8> Ops;
11340     for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
11341       SDValue LHSOp = LHS.getOperand(i);
11342       SDValue RHSOp = RHS.getOperand(i);
11343
11344       // Can't fold divide by zero.
11345       if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
11346           N->getOpcode() == ISD::FDIV) {
11347         if ((RHSOp.getOpcode() == ISD::Constant &&
11348              cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
11349             (RHSOp.getOpcode() == ISD::ConstantFP &&
11350              cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
11351           break;
11352       }
11353
11354       EVT VT = LHSOp.getValueType();
11355       EVT RVT = RHSOp.getValueType();
11356       if (RVT != VT) {
11357         // Integer BUILD_VECTOR operands may have types larger than the element
11358         // size (e.g., when the element type is not legal).  Prior to type
11359         // legalization, the types may not match between the two BUILD_VECTORS.
11360         // Truncate one of the operands to make them match.
11361         if (RVT.getSizeInBits() > VT.getSizeInBits()) {
11362           RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
11363         } else {
11364           LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
11365           VT = RVT;
11366         }
11367       }
11368       SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
11369                                    LHSOp, RHSOp);
11370       if (FoldOp.getOpcode() != ISD::UNDEF &&
11371           FoldOp.getOpcode() != ISD::Constant &&
11372           FoldOp.getOpcode() != ISD::ConstantFP)
11373         break;
11374       Ops.push_back(FoldOp);
11375       AddToWorklist(FoldOp.getNode());
11376     }
11377
11378     if (Ops.size() == LHS.getNumOperands())
11379       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
11380   }
11381
11382   // Type legalization might introduce new shuffles in the DAG.
11383   // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
11384   //   -> (shuffle (VBinOp (A, B)), Undef, Mask).
11385   if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
11386       isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
11387       LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
11388       RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
11389     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
11390     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
11391
11392     if (SVN0->getMask().equals(SVN1->getMask())) {
11393       EVT VT = N->getValueType(0);
11394       SDValue UndefVector = LHS.getOperand(1);
11395       SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
11396                                      LHS.getOperand(0), RHS.getOperand(0));
11397       AddUsersToWorklist(N);
11398       return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
11399                                   &SVN0->getMask()[0]);
11400     }
11401   }
11402
11403   return SDValue();
11404 }
11405
11406 /// Visit a binary vector operation, like FABS/FNEG.
11407 SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
11408   assert(N->getValueType(0).isVector() &&
11409          "SimplifyVUnaryOp only works on vectors!");
11410
11411   SDValue N0 = N->getOperand(0);
11412
11413   if (N0.getOpcode() != ISD::BUILD_VECTOR)
11414     return SDValue();
11415
11416   // Operand is a BUILD_VECTOR node, see if we can constant fold it.
11417   SmallVector<SDValue, 8> Ops;
11418   for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
11419     SDValue Op = N0.getOperand(i);
11420     if (Op.getOpcode() != ISD::UNDEF &&
11421         Op.getOpcode() != ISD::ConstantFP)
11422       break;
11423     EVT EltVT = Op.getValueType();
11424     SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op);
11425     if (FoldOp.getOpcode() != ISD::UNDEF &&
11426         FoldOp.getOpcode() != ISD::ConstantFP)
11427       break;
11428     Ops.push_back(FoldOp);
11429     AddToWorklist(FoldOp.getNode());
11430   }
11431
11432   if (Ops.size() != N0.getNumOperands())
11433     return SDValue();
11434
11435   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), N0.getValueType(), Ops);
11436 }
11437
11438 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
11439                                     SDValue N1, SDValue N2){
11440   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
11441
11442   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
11443                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
11444
11445   // If we got a simplified select_cc node back from SimplifySelectCC, then
11446   // break it down into a new SETCC node, and a new SELECT node, and then return
11447   // the SELECT node, since we were called with a SELECT node.
11448   if (SCC.getNode()) {
11449     // Check to see if we got a select_cc back (to turn into setcc/select).
11450     // Otherwise, just return whatever node we got back, like fabs.
11451     if (SCC.getOpcode() == ISD::SELECT_CC) {
11452       SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
11453                                   N0.getValueType(),
11454                                   SCC.getOperand(0), SCC.getOperand(1),
11455                                   SCC.getOperand(4));
11456       AddToWorklist(SETCC.getNode());
11457       return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
11458                            SCC.getOperand(2), SCC.getOperand(3));
11459     }
11460
11461     return SCC;
11462   }
11463   return SDValue();
11464 }
11465
11466 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
11467 /// being selected between, see if we can simplify the select.  Callers of this
11468 /// should assume that TheSelect is deleted if this returns true.  As such, they
11469 /// should return the appropriate thing (e.g. the node) back to the top-level of
11470 /// the DAG combiner loop to avoid it being looked at.
11471 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
11472                                     SDValue RHS) {
11473
11474   // Cannot simplify select with vector condition
11475   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
11476
11477   // If this is a select from two identical things, try to pull the operation
11478   // through the select.
11479   if (LHS.getOpcode() != RHS.getOpcode() ||
11480       !LHS.hasOneUse() || !RHS.hasOneUse())
11481     return false;
11482
11483   // If this is a load and the token chain is identical, replace the select
11484   // of two loads with a load through a select of the address to load from.
11485   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
11486   // constants have been dropped into the constant pool.
11487   if (LHS.getOpcode() == ISD::LOAD) {
11488     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
11489     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
11490
11491     // Token chains must be identical.
11492     if (LHS.getOperand(0) != RHS.getOperand(0) ||
11493         // Do not let this transformation reduce the number of volatile loads.
11494         LLD->isVolatile() || RLD->isVolatile() ||
11495         // If this is an EXTLOAD, the VT's must match.
11496         LLD->getMemoryVT() != RLD->getMemoryVT() ||
11497         // If this is an EXTLOAD, the kind of extension must match.
11498         (LLD->getExtensionType() != RLD->getExtensionType() &&
11499          // The only exception is if one of the extensions is anyext.
11500          LLD->getExtensionType() != ISD::EXTLOAD &&
11501          RLD->getExtensionType() != ISD::EXTLOAD) ||
11502         // FIXME: this discards src value information.  This is
11503         // over-conservative. It would be beneficial to be able to remember
11504         // both potential memory locations.  Since we are discarding
11505         // src value info, don't do the transformation if the memory
11506         // locations are not in the default address space.
11507         LLD->getPointerInfo().getAddrSpace() != 0 ||
11508         RLD->getPointerInfo().getAddrSpace() != 0 ||
11509         !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
11510                                       LLD->getBasePtr().getValueType()))
11511       return false;
11512
11513     // Check that the select condition doesn't reach either load.  If so,
11514     // folding this will induce a cycle into the DAG.  If not, this is safe to
11515     // xform, so create a select of the addresses.
11516     SDValue Addr;
11517     if (TheSelect->getOpcode() == ISD::SELECT) {
11518       SDNode *CondNode = TheSelect->getOperand(0).getNode();
11519       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
11520           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
11521         return false;
11522       // The loads must not depend on one another.
11523       if (LLD->isPredecessorOf(RLD) ||
11524           RLD->isPredecessorOf(LLD))
11525         return false;
11526       Addr = DAG.getSelect(SDLoc(TheSelect),
11527                            LLD->getBasePtr().getValueType(),
11528                            TheSelect->getOperand(0), LLD->getBasePtr(),
11529                            RLD->getBasePtr());
11530     } else {  // Otherwise SELECT_CC
11531       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
11532       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
11533
11534       if ((LLD->hasAnyUseOfValue(1) &&
11535            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
11536           (RLD->hasAnyUseOfValue(1) &&
11537            (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
11538         return false;
11539
11540       Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
11541                          LLD->getBasePtr().getValueType(),
11542                          TheSelect->getOperand(0),
11543                          TheSelect->getOperand(1),
11544                          LLD->getBasePtr(), RLD->getBasePtr(),
11545                          TheSelect->getOperand(4));
11546     }
11547
11548     SDValue Load;
11549     // It is safe to replace the two loads if they have different alignments,
11550     // but the new load must be the minimum (most restrictive) alignment of the
11551     // inputs.
11552     bool isInvariant = LLD->isInvariant() & RLD->isInvariant();
11553     unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
11554     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
11555       Load = DAG.getLoad(TheSelect->getValueType(0),
11556                          SDLoc(TheSelect),
11557                          // FIXME: Discards pointer and AA info.
11558                          LLD->getChain(), Addr, MachinePointerInfo(),
11559                          LLD->isVolatile(), LLD->isNonTemporal(),
11560                          isInvariant, Alignment);
11561     } else {
11562       Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
11563                             RLD->getExtensionType() : LLD->getExtensionType(),
11564                             SDLoc(TheSelect),
11565                             TheSelect->getValueType(0),
11566                             // FIXME: Discards pointer and AA info.
11567                             LLD->getChain(), Addr, MachinePointerInfo(),
11568                             LLD->getMemoryVT(), LLD->isVolatile(),
11569                             LLD->isNonTemporal(), isInvariant, Alignment);
11570     }
11571
11572     // Users of the select now use the result of the load.
11573     CombineTo(TheSelect, Load);
11574
11575     // Users of the old loads now use the new load's chain.  We know the
11576     // old-load value is dead now.
11577     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
11578     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
11579     return true;
11580   }
11581
11582   return false;
11583 }
11584
11585 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
11586 /// where 'cond' is the comparison specified by CC.
11587 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
11588                                       SDValue N2, SDValue N3,
11589                                       ISD::CondCode CC, bool NotExtCompare) {
11590   // (x ? y : y) -> y.
11591   if (N2 == N3) return N2;
11592
11593   EVT VT = N2.getValueType();
11594   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
11595   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
11596   ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
11597
11598   // Determine if the condition we're dealing with is constant
11599   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
11600                               N0, N1, CC, DL, false);
11601   if (SCC.getNode()) AddToWorklist(SCC.getNode());
11602   ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
11603
11604   // fold select_cc true, x, y -> x
11605   if (SCCC && !SCCC->isNullValue())
11606     return N2;
11607   // fold select_cc false, x, y -> y
11608   if (SCCC && SCCC->isNullValue())
11609     return N3;
11610
11611   // Check to see if we can simplify the select into an fabs node
11612   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
11613     // Allow either -0.0 or 0.0
11614     if (CFP->getValueAPF().isZero()) {
11615       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
11616       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
11617           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
11618           N2 == N3.getOperand(0))
11619         return DAG.getNode(ISD::FABS, DL, VT, N0);
11620
11621       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
11622       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
11623           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
11624           N2.getOperand(0) == N3)
11625         return DAG.getNode(ISD::FABS, DL, VT, N3);
11626     }
11627   }
11628
11629   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
11630   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
11631   // in it.  This is a win when the constant is not otherwise available because
11632   // it replaces two constant pool loads with one.  We only do this if the FP
11633   // type is known to be legal, because if it isn't, then we are before legalize
11634   // types an we want the other legalization to happen first (e.g. to avoid
11635   // messing with soft float) and if the ConstantFP is not legal, because if
11636   // it is legal, we may not need to store the FP constant in a constant pool.
11637   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
11638     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
11639       if (TLI.isTypeLegal(N2.getValueType()) &&
11640           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
11641                TargetLowering::Legal &&
11642            !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
11643            !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
11644           // If both constants have multiple uses, then we won't need to do an
11645           // extra load, they are likely around in registers for other users.
11646           (TV->hasOneUse() || FV->hasOneUse())) {
11647         Constant *Elts[] = {
11648           const_cast<ConstantFP*>(FV->getConstantFPValue()),
11649           const_cast<ConstantFP*>(TV->getConstantFPValue())
11650         };
11651         Type *FPTy = Elts[0]->getType();
11652         const DataLayout &TD = *TLI.getDataLayout();
11653
11654         // Create a ConstantArray of the two constants.
11655         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
11656         SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
11657                                             TD.getPrefTypeAlignment(FPTy));
11658         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
11659
11660         // Get the offsets to the 0 and 1 element of the array so that we can
11661         // select between them.
11662         SDValue Zero = DAG.getIntPtrConstant(0);
11663         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
11664         SDValue One = DAG.getIntPtrConstant(EltSize);
11665
11666         SDValue Cond = DAG.getSetCC(DL,
11667                                     getSetCCResultType(N0.getValueType()),
11668                                     N0, N1, CC);
11669         AddToWorklist(Cond.getNode());
11670         SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
11671                                           Cond, One, Zero);
11672         AddToWorklist(CstOffset.getNode());
11673         CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
11674                             CstOffset);
11675         AddToWorklist(CPIdx.getNode());
11676         return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
11677                            MachinePointerInfo::getConstantPool(), false,
11678                            false, false, Alignment);
11679
11680       }
11681     }
11682
11683   // Check to see if we can perform the "gzip trick", transforming
11684   // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
11685   if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
11686       (N1C->isNullValue() ||                         // (a < 0) ? b : 0
11687        (N1C->getAPIntValue() == 1 && N0 == N2))) {   // (a < 1) ? a : 0
11688     EVT XType = N0.getValueType();
11689     EVT AType = N2.getValueType();
11690     if (XType.bitsGE(AType)) {
11691       // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
11692       // single-bit constant.
11693       if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
11694         unsigned ShCtV = N2C->getAPIntValue().logBase2();
11695         ShCtV = XType.getSizeInBits()-ShCtV-1;
11696         SDValue ShCt = DAG.getConstant(ShCtV,
11697                                        getShiftAmountTy(N0.getValueType()));
11698         SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
11699                                     XType, N0, ShCt);
11700         AddToWorklist(Shift.getNode());
11701
11702         if (XType.bitsGT(AType)) {
11703           Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11704           AddToWorklist(Shift.getNode());
11705         }
11706
11707         return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11708       }
11709
11710       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
11711                                   XType, N0,
11712                                   DAG.getConstant(XType.getSizeInBits()-1,
11713                                          getShiftAmountTy(N0.getValueType())));
11714       AddToWorklist(Shift.getNode());
11715
11716       if (XType.bitsGT(AType)) {
11717         Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11718         AddToWorklist(Shift.getNode());
11719       }
11720
11721       return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11722     }
11723   }
11724
11725   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
11726   // where y is has a single bit set.
11727   // A plaintext description would be, we can turn the SELECT_CC into an AND
11728   // when the condition can be materialized as an all-ones register.  Any
11729   // single bit-test can be materialized as an all-ones register with
11730   // shift-left and shift-right-arith.
11731   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
11732       N0->getValueType(0) == VT &&
11733       N1C && N1C->isNullValue() &&
11734       N2C && N2C->isNullValue()) {
11735     SDValue AndLHS = N0->getOperand(0);
11736     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
11737     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
11738       // Shift the tested bit over the sign bit.
11739       APInt AndMask = ConstAndRHS->getAPIntValue();
11740       SDValue ShlAmt =
11741         DAG.getConstant(AndMask.countLeadingZeros(),
11742                         getShiftAmountTy(AndLHS.getValueType()));
11743       SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
11744
11745       // Now arithmetic right shift it all the way over, so the result is either
11746       // all-ones, or zero.
11747       SDValue ShrAmt =
11748         DAG.getConstant(AndMask.getBitWidth()-1,
11749                         getShiftAmountTy(Shl.getValueType()));
11750       SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
11751
11752       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
11753     }
11754   }
11755
11756   // fold select C, 16, 0 -> shl C, 4
11757   if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
11758       TLI.getBooleanContents(N0.getValueType()) ==
11759           TargetLowering::ZeroOrOneBooleanContent) {
11760
11761     // If the caller doesn't want us to simplify this into a zext of a compare,
11762     // don't do it.
11763     if (NotExtCompare && N2C->getAPIntValue() == 1)
11764       return SDValue();
11765
11766     // Get a SetCC of the condition
11767     // NOTE: Don't create a SETCC if it's not legal on this target.
11768     if (!LegalOperations ||
11769         TLI.isOperationLegal(ISD::SETCC,
11770           LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
11771       SDValue Temp, SCC;
11772       // cast from setcc result type to select result type
11773       if (LegalTypes) {
11774         SCC  = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
11775                             N0, N1, CC);
11776         if (N2.getValueType().bitsLT(SCC.getValueType()))
11777           Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
11778                                         N2.getValueType());
11779         else
11780           Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11781                              N2.getValueType(), SCC);
11782       } else {
11783         SCC  = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
11784         Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11785                            N2.getValueType(), SCC);
11786       }
11787
11788       AddToWorklist(SCC.getNode());
11789       AddToWorklist(Temp.getNode());
11790
11791       if (N2C->getAPIntValue() == 1)
11792         return Temp;
11793
11794       // shl setcc result by log2 n2c
11795       return DAG.getNode(
11796           ISD::SHL, DL, N2.getValueType(), Temp,
11797           DAG.getConstant(N2C->getAPIntValue().logBase2(),
11798                           getShiftAmountTy(Temp.getValueType())));
11799     }
11800   }
11801
11802   // Check to see if this is the equivalent of setcc
11803   // FIXME: Turn all of these into setcc if setcc if setcc is legal
11804   // otherwise, go ahead with the folds.
11805   if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
11806     EVT XType = N0.getValueType();
11807     if (!LegalOperations ||
11808         TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
11809       SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
11810       if (Res.getValueType() != VT)
11811         Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
11812       return Res;
11813     }
11814
11815     // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
11816     if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
11817         (!LegalOperations ||
11818          TLI.isOperationLegal(ISD::CTLZ, XType))) {
11819       SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
11820       return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
11821                          DAG.getConstant(Log2_32(XType.getSizeInBits()),
11822                                        getShiftAmountTy(Ctlz.getValueType())));
11823     }
11824     // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
11825     if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
11826       SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
11827                                   XType, DAG.getConstant(0, XType), N0);
11828       SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
11829       return DAG.getNode(ISD::SRL, DL, XType,
11830                          DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
11831                          DAG.getConstant(XType.getSizeInBits()-1,
11832                                          getShiftAmountTy(XType)));
11833     }
11834     // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
11835     if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
11836       SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
11837                                  DAG.getConstant(XType.getSizeInBits()-1,
11838                                          getShiftAmountTy(N0.getValueType())));
11839       return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
11840     }
11841   }
11842
11843   // Check to see if this is an integer abs.
11844   // select_cc setg[te] X,  0,  X, -X ->
11845   // select_cc setgt    X, -1,  X, -X ->
11846   // select_cc setl[te] X,  0, -X,  X ->
11847   // select_cc setlt    X,  1, -X,  X ->
11848   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
11849   if (N1C) {
11850     ConstantSDNode *SubC = nullptr;
11851     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
11852          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
11853         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
11854       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
11855     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
11856               (N1C->isOne() && CC == ISD::SETLT)) &&
11857              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
11858       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
11859
11860     EVT XType = N0.getValueType();
11861     if (SubC && SubC->isNullValue() && XType.isInteger()) {
11862       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
11863                                   N0,
11864                                   DAG.getConstant(XType.getSizeInBits()-1,
11865                                          getShiftAmountTy(N0.getValueType())));
11866       SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
11867                                 XType, N0, Shift);
11868       AddToWorklist(Shift.getNode());
11869       AddToWorklist(Add.getNode());
11870       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
11871     }
11872   }
11873
11874   return SDValue();
11875 }
11876
11877 /// This is a stub for TargetLowering::SimplifySetCC.
11878 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
11879                                    SDValue N1, ISD::CondCode Cond,
11880                                    SDLoc DL, bool foldBooleans) {
11881   TargetLowering::DAGCombinerInfo
11882     DagCombineInfo(DAG, Level, false, this);
11883   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
11884 }
11885
11886 /// Given an ISD::SDIV node expressing a divide by constant, return
11887 /// a DAG expression to select that will generate the same value by multiplying
11888 /// by a magic number.
11889 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
11890 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
11891   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11892   if (!C)
11893     return SDValue();
11894
11895   // Avoid division by zero.
11896   if (!C->getAPIntValue())
11897     return SDValue();
11898
11899   std::vector<SDNode*> Built;
11900   SDValue S =
11901       TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
11902
11903   for (SDNode *N : Built)
11904     AddToWorklist(N);
11905   return S;
11906 }
11907
11908 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
11909 /// DAG expression that will generate the same value by right shifting.
11910 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
11911   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11912   if (!C)
11913     return SDValue();
11914
11915   // Avoid division by zero.
11916   if (!C->getAPIntValue())
11917     return SDValue();
11918
11919   std::vector<SDNode *> Built;
11920   SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
11921
11922   for (SDNode *N : Built)
11923     AddToWorklist(N);
11924   return S;
11925 }
11926
11927 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
11928 /// expression that will generate the same value by multiplying by a magic
11929 /// number.
11930 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
11931 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
11932   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11933   if (!C)
11934     return SDValue();
11935
11936   // Avoid division by zero.
11937   if (!C->getAPIntValue())
11938     return SDValue();
11939
11940   std::vector<SDNode*> Built;
11941   SDValue S =
11942       TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
11943
11944   for (SDNode *N : Built)
11945     AddToWorklist(N);
11946   return S;
11947 }
11948
11949 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op) {
11950   if (Level >= AfterLegalizeDAG)
11951     return SDValue();
11952
11953   // Expose the DAG combiner to the target combiner implementations.
11954   TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
11955
11956   unsigned Iterations = 0;
11957   if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) {
11958     if (Iterations) {
11959       // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
11960       // For the reciprocal, we need to find the zero of the function:
11961       //   F(X) = A X - 1 [which has a zero at X = 1/A]
11962       //     =>
11963       //   X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
11964       //     does not require additional intermediate precision]
11965       EVT VT = Op.getValueType();
11966       SDLoc DL(Op);
11967       SDValue FPOne = DAG.getConstantFP(1.0, VT);
11968
11969       AddToWorklist(Est.getNode());
11970
11971       // Newton iterations: Est = Est + Est (1 - Arg * Est)
11972       for (unsigned i = 0; i < Iterations; ++i) {
11973         SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est);
11974         AddToWorklist(NewEst.getNode());
11975
11976         NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst);
11977         AddToWorklist(NewEst.getNode());
11978
11979         NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
11980         AddToWorklist(NewEst.getNode());
11981
11982         Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst);
11983         AddToWorklist(Est.getNode());
11984       }
11985     }
11986     return Est;
11987   }
11988
11989   return SDValue();
11990 }
11991
11992 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
11993 /// For the reciprocal sqrt, we need to find the zero of the function:
11994 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
11995 ///     =>
11996 ///   X_{i+1} = X_i (1.5 - A X_i^2 / 2)
11997 /// As a result, we precompute A/2 prior to the iteration loop.
11998 SDValue DAGCombiner::BuildRsqrtNROneConst(SDValue Arg, SDValue Est,
11999                                           unsigned Iterations) {
12000   EVT VT = Arg.getValueType();
12001   SDLoc DL(Arg);
12002   SDValue ThreeHalves = DAG.getConstantFP(1.5, VT);
12003
12004   // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
12005   // this entire sequence requires only one FP constant.
12006   SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg);
12007   AddToWorklist(HalfArg.getNode());
12008
12009   HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg);
12010   AddToWorklist(HalfArg.getNode());
12011
12012   // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
12013   for (unsigned i = 0; i < Iterations; ++i) {
12014     SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
12015     AddToWorklist(NewEst.getNode());
12016
12017     NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst);
12018     AddToWorklist(NewEst.getNode());
12019
12020     NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst);
12021     AddToWorklist(NewEst.getNode());
12022
12023     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
12024     AddToWorklist(Est.getNode());
12025   }
12026   return Est;
12027 }
12028
12029 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
12030 /// For the reciprocal sqrt, we need to find the zero of the function:
12031 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
12032 ///     =>
12033 ///   X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
12034 SDValue DAGCombiner::BuildRsqrtNRTwoConst(SDValue Arg, SDValue Est,
12035                                           unsigned Iterations) {
12036   EVT VT = Arg.getValueType();
12037   SDLoc DL(Arg);
12038   SDValue MinusThree = DAG.getConstantFP(-3.0, VT);
12039   SDValue MinusHalf = DAG.getConstantFP(-0.5, VT);
12040
12041   // Newton iterations: Est = -0.5 * Est * (-3.0 + Arg * Est * Est)
12042   for (unsigned i = 0; i < Iterations; ++i) {
12043     SDValue HalfEst = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf);
12044     AddToWorklist(HalfEst.getNode());
12045
12046     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
12047     AddToWorklist(Est.getNode());
12048
12049     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg);
12050     AddToWorklist(Est.getNode());
12051
12052     Est = DAG.getNode(ISD::FADD, DL, VT, Est, MinusThree);
12053     AddToWorklist(Est.getNode());
12054
12055     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, HalfEst);
12056     AddToWorklist(Est.getNode());
12057   }
12058   return Est;
12059 }
12060
12061 SDValue DAGCombiner::BuildRsqrtEstimate(SDValue Op) {
12062   if (Level >= AfterLegalizeDAG)
12063     return SDValue();
12064
12065   // Expose the DAG combiner to the target combiner implementations.
12066   TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
12067   unsigned Iterations = 0;
12068   bool UseOneConstNR = false;
12069   if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations, UseOneConstNR)) {
12070     AddToWorklist(Est.getNode());
12071     if (Iterations) {
12072       Est = UseOneConstNR ?
12073         BuildRsqrtNROneConst(Op, Est, Iterations) :
12074         BuildRsqrtNRTwoConst(Op, Est, Iterations);
12075     }
12076     return Est;
12077   }
12078
12079   return SDValue();
12080 }
12081
12082 /// Return true if base is a frame index, which is known not to alias with
12083 /// anything but itself.  Provides base object and offset as results.
12084 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
12085                            const GlobalValue *&GV, const void *&CV) {
12086   // Assume it is a primitive operation.
12087   Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
12088
12089   // If it's an adding a simple constant then integrate the offset.
12090   if (Base.getOpcode() == ISD::ADD) {
12091     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
12092       Base = Base.getOperand(0);
12093       Offset += C->getZExtValue();
12094     }
12095   }
12096
12097   // Return the underlying GlobalValue, and update the Offset.  Return false
12098   // for GlobalAddressSDNode since the same GlobalAddress may be represented
12099   // by multiple nodes with different offsets.
12100   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
12101     GV = G->getGlobal();
12102     Offset += G->getOffset();
12103     return false;
12104   }
12105
12106   // Return the underlying Constant value, and update the Offset.  Return false
12107   // for ConstantSDNodes since the same constant pool entry may be represented
12108   // by multiple nodes with different offsets.
12109   if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
12110     CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
12111                                          : (const void *)C->getConstVal();
12112     Offset += C->getOffset();
12113     return false;
12114   }
12115   // If it's any of the following then it can't alias with anything but itself.
12116   return isa<FrameIndexSDNode>(Base);
12117 }
12118
12119 /// Return true if there is any possibility that the two addresses overlap.
12120 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
12121   // If they are the same then they must be aliases.
12122   if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
12123
12124   // If they are both volatile then they cannot be reordered.
12125   if (Op0->isVolatile() && Op1->isVolatile()) return true;
12126
12127   // Gather base node and offset information.
12128   SDValue Base1, Base2;
12129   int64_t Offset1, Offset2;
12130   const GlobalValue *GV1, *GV2;
12131   const void *CV1, *CV2;
12132   bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
12133                                       Base1, Offset1, GV1, CV1);
12134   bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
12135                                       Base2, Offset2, GV2, CV2);
12136
12137   // If they have a same base address then check to see if they overlap.
12138   if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
12139     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
12140              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
12141
12142   // It is possible for different frame indices to alias each other, mostly
12143   // when tail call optimization reuses return address slots for arguments.
12144   // To catch this case, look up the actual index of frame indices to compute
12145   // the real alias relationship.
12146   if (isFrameIndex1 && isFrameIndex2) {
12147     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12148     Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
12149     Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
12150     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
12151              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
12152   }
12153
12154   // Otherwise, if we know what the bases are, and they aren't identical, then
12155   // we know they cannot alias.
12156   if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
12157     return false;
12158
12159   // If we know required SrcValue1 and SrcValue2 have relatively large alignment
12160   // compared to the size and offset of the access, we may be able to prove they
12161   // do not alias.  This check is conservative for now to catch cases created by
12162   // splitting vector types.
12163   if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
12164       (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
12165       (Op0->getMemoryVT().getSizeInBits() >> 3 ==
12166        Op1->getMemoryVT().getSizeInBits() >> 3) &&
12167       (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
12168     int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
12169     int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
12170
12171     // There is no overlap between these relatively aligned accesses of similar
12172     // size, return no alias.
12173     if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
12174         (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
12175       return false;
12176   }
12177
12178   bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
12179                    ? CombinerGlobalAA
12180                    : DAG.getSubtarget().useAA();
12181 #ifndef NDEBUG
12182   if (CombinerAAOnlyFunc.getNumOccurrences() &&
12183       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
12184     UseAA = false;
12185 #endif
12186   if (UseAA &&
12187       Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
12188     // Use alias analysis information.
12189     int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
12190                                  Op1->getSrcValueOffset());
12191     int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
12192         Op0->getSrcValueOffset() - MinOffset;
12193     int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
12194         Op1->getSrcValueOffset() - MinOffset;
12195     AliasAnalysis::AliasResult AAResult =
12196         AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(),
12197                                          Overlap1,
12198                                          UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
12199                  AliasAnalysis::Location(Op1->getMemOperand()->getValue(),
12200                                          Overlap2,
12201                                          UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
12202     if (AAResult == AliasAnalysis::NoAlias)
12203       return false;
12204   }
12205
12206   // Otherwise we have to assume they alias.
12207   return true;
12208 }
12209
12210 /// Walk up chain skipping non-aliasing memory nodes,
12211 /// looking for aliasing nodes and adding them to the Aliases vector.
12212 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
12213                                    SmallVectorImpl<SDValue> &Aliases) {
12214   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
12215   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
12216
12217   // Get alias information for node.
12218   bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
12219
12220   // Starting off.
12221   Chains.push_back(OriginalChain);
12222   unsigned Depth = 0;
12223
12224   // Look at each chain and determine if it is an alias.  If so, add it to the
12225   // aliases list.  If not, then continue up the chain looking for the next
12226   // candidate.
12227   while (!Chains.empty()) {
12228     SDValue Chain = Chains.back();
12229     Chains.pop_back();
12230
12231     // For TokenFactor nodes, look at each operand and only continue up the
12232     // chain until we find two aliases.  If we've seen two aliases, assume we'll
12233     // find more and revert to original chain since the xform is unlikely to be
12234     // profitable.
12235     //
12236     // FIXME: The depth check could be made to return the last non-aliasing
12237     // chain we found before we hit a tokenfactor rather than the original
12238     // chain.
12239     if (Depth > 6 || Aliases.size() == 2) {
12240       Aliases.clear();
12241       Aliases.push_back(OriginalChain);
12242       return;
12243     }
12244
12245     // Don't bother if we've been before.
12246     if (!Visited.insert(Chain.getNode()))
12247       continue;
12248
12249     switch (Chain.getOpcode()) {
12250     case ISD::EntryToken:
12251       // Entry token is ideal chain operand, but handled in FindBetterChain.
12252       break;
12253
12254     case ISD::LOAD:
12255     case ISD::STORE: {
12256       // Get alias information for Chain.
12257       bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
12258           !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
12259
12260       // If chain is alias then stop here.
12261       if (!(IsLoad && IsOpLoad) &&
12262           isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
12263         Aliases.push_back(Chain);
12264       } else {
12265         // Look further up the chain.
12266         Chains.push_back(Chain.getOperand(0));
12267         ++Depth;
12268       }
12269       break;
12270     }
12271
12272     case ISD::TokenFactor:
12273       // We have to check each of the operands of the token factor for "small"
12274       // token factors, so we queue them up.  Adding the operands to the queue
12275       // (stack) in reverse order maintains the original order and increases the
12276       // likelihood that getNode will find a matching token factor (CSE.)
12277       if (Chain.getNumOperands() > 16) {
12278         Aliases.push_back(Chain);
12279         break;
12280       }
12281       for (unsigned n = Chain.getNumOperands(); n;)
12282         Chains.push_back(Chain.getOperand(--n));
12283       ++Depth;
12284       break;
12285
12286     default:
12287       // For all other instructions we will just have to take what we can get.
12288       Aliases.push_back(Chain);
12289       break;
12290     }
12291   }
12292
12293   // We need to be careful here to also search for aliases through the
12294   // value operand of a store, etc. Consider the following situation:
12295   //   Token1 = ...
12296   //   L1 = load Token1, %52
12297   //   S1 = store Token1, L1, %51
12298   //   L2 = load Token1, %52+8
12299   //   S2 = store Token1, L2, %51+8
12300   //   Token2 = Token(S1, S2)
12301   //   L3 = load Token2, %53
12302   //   S3 = store Token2, L3, %52
12303   //   L4 = load Token2, %53+8
12304   //   S4 = store Token2, L4, %52+8
12305   // If we search for aliases of S3 (which loads address %52), and we look
12306   // only through the chain, then we'll miss the trivial dependence on L1
12307   // (which also loads from %52). We then might change all loads and
12308   // stores to use Token1 as their chain operand, which could result in
12309   // copying %53 into %52 before copying %52 into %51 (which should
12310   // happen first).
12311   //
12312   // The problem is, however, that searching for such data dependencies
12313   // can become expensive, and the cost is not directly related to the
12314   // chain depth. Instead, we'll rule out such configurations here by
12315   // insisting that we've visited all chain users (except for users
12316   // of the original chain, which is not necessary). When doing this,
12317   // we need to look through nodes we don't care about (otherwise, things
12318   // like register copies will interfere with trivial cases).
12319
12320   SmallVector<const SDNode *, 16> Worklist;
12321   for (const SDNode *N : Visited)
12322     if (N != OriginalChain.getNode())
12323       Worklist.push_back(N);
12324
12325   while (!Worklist.empty()) {
12326     const SDNode *M = Worklist.pop_back_val();
12327
12328     // We have already visited M, and want to make sure we've visited any uses
12329     // of M that we care about. For uses that we've not visisted, and don't
12330     // care about, queue them to the worklist.
12331
12332     for (SDNode::use_iterator UI = M->use_begin(),
12333          UIE = M->use_end(); UI != UIE; ++UI)
12334       if (UI.getUse().getValueType() == MVT::Other && Visited.insert(*UI)) {
12335         if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
12336           // We've not visited this use, and we care about it (it could have an
12337           // ordering dependency with the original node).
12338           Aliases.clear();
12339           Aliases.push_back(OriginalChain);
12340           return;
12341         }
12342
12343         // We've not visited this use, but we don't care about it. Mark it as
12344         // visited and enqueue it to the worklist.
12345         Worklist.push_back(*UI);
12346       }
12347   }
12348 }
12349
12350 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
12351 /// (aliasing node.)
12352 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
12353   SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
12354
12355   // Accumulate all the aliases to this node.
12356   GatherAllAliases(N, OldChain, Aliases);
12357
12358   // If no operands then chain to entry token.
12359   if (Aliases.size() == 0)
12360     return DAG.getEntryNode();
12361
12362   // If a single operand then chain to it.  We don't need to revisit it.
12363   if (Aliases.size() == 1)
12364     return Aliases[0];
12365
12366   // Construct a custom tailored token factor.
12367   return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
12368 }
12369
12370 /// This is the entry point for the file.
12371 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
12372                            CodeGenOpt::Level OptLevel) {
12373   /// This is the main entry point to this class.
12374   DAGCombiner(*this, AA, OptLevel).Run(Level);
12375 }