DAGCombiner: Use isNullConstant() where possible
[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/SetVector.h"
21 #include "llvm/ADT/SmallBitVector.h"
22 #include "llvm/ADT/SmallPtrSet.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 visitANDLike(SDValue N0, SDValue N1, SDNode *LocReference);
250     SDValue visitOR(SDNode *N);
251     SDValue visitORLike(SDValue N0, SDValue N1, SDNode *LocReference);
252     SDValue visitXOR(SDNode *N);
253     SDValue SimplifyVBinOp(SDNode *N);
254     SDValue visitSHL(SDNode *N);
255     SDValue visitSRA(SDNode *N);
256     SDValue visitSRL(SDNode *N);
257     SDValue visitRotate(SDNode *N);
258     SDValue visitCTLZ(SDNode *N);
259     SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
260     SDValue visitCTTZ(SDNode *N);
261     SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
262     SDValue visitCTPOP(SDNode *N);
263     SDValue visitSELECT(SDNode *N);
264     SDValue visitVSELECT(SDNode *N);
265     SDValue visitSELECT_CC(SDNode *N);
266     SDValue visitSETCC(SDNode *N);
267     SDValue visitSIGN_EXTEND(SDNode *N);
268     SDValue visitZERO_EXTEND(SDNode *N);
269     SDValue visitANY_EXTEND(SDNode *N);
270     SDValue visitSIGN_EXTEND_INREG(SDNode *N);
271     SDValue visitTRUNCATE(SDNode *N);
272     SDValue visitBITCAST(SDNode *N);
273     SDValue visitBUILD_PAIR(SDNode *N);
274     SDValue visitFADD(SDNode *N);
275     SDValue visitFSUB(SDNode *N);
276     SDValue visitFMUL(SDNode *N);
277     SDValue visitFMA(SDNode *N);
278     SDValue visitFDIV(SDNode *N);
279     SDValue visitFREM(SDNode *N);
280     SDValue visitFSQRT(SDNode *N);
281     SDValue visitFCOPYSIGN(SDNode *N);
282     SDValue visitSINT_TO_FP(SDNode *N);
283     SDValue visitUINT_TO_FP(SDNode *N);
284     SDValue visitFP_TO_SINT(SDNode *N);
285     SDValue visitFP_TO_UINT(SDNode *N);
286     SDValue visitFP_ROUND(SDNode *N);
287     SDValue visitFP_ROUND_INREG(SDNode *N);
288     SDValue visitFP_EXTEND(SDNode *N);
289     SDValue visitFNEG(SDNode *N);
290     SDValue visitFABS(SDNode *N);
291     SDValue visitFCEIL(SDNode *N);
292     SDValue visitFTRUNC(SDNode *N);
293     SDValue visitFFLOOR(SDNode *N);
294     SDValue visitFMINNUM(SDNode *N);
295     SDValue visitFMAXNUM(SDNode *N);
296     SDValue visitBRCOND(SDNode *N);
297     SDValue visitBR_CC(SDNode *N);
298     SDValue visitLOAD(SDNode *N);
299     SDValue visitSTORE(SDNode *N);
300     SDValue visitINSERT_VECTOR_ELT(SDNode *N);
301     SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
302     SDValue visitBUILD_VECTOR(SDNode *N);
303     SDValue visitCONCAT_VECTORS(SDNode *N);
304     SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
305     SDValue visitVECTOR_SHUFFLE(SDNode *N);
306     SDValue visitSCALAR_TO_VECTOR(SDNode *N);
307     SDValue visitINSERT_SUBVECTOR(SDNode *N);
308     SDValue visitMLOAD(SDNode *N);
309     SDValue visitMSTORE(SDNode *N);
310     SDValue visitMGATHER(SDNode *N);
311     SDValue visitMSCATTER(SDNode *N);
312     SDValue visitFP_TO_FP16(SDNode *N);
313
314     SDValue visitFADDForFMACombine(SDNode *N);
315     SDValue visitFSUBForFMACombine(SDNode *N);
316
317     SDValue XformToShuffleWithZero(SDNode *N);
318     SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
319
320     SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
321
322     bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
323     SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
324     SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
325     SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
326                              SDValue N3, ISD::CondCode CC,
327                              bool NotExtCompare = false);
328     SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
329                           SDLoc DL, bool foldBooleans = true);
330
331     bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
332                            SDValue &CC) const;
333     bool isOneUseSetCC(SDValue N) const;
334
335     SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
336                                          unsigned HiOp);
337     SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
338     SDValue CombineExtLoad(SDNode *N);
339     SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
340     SDValue BuildSDIV(SDNode *N);
341     SDValue BuildSDIVPow2(SDNode *N);
342     SDValue BuildUDIV(SDNode *N);
343     SDValue BuildReciprocalEstimate(SDValue Op);
344     SDValue BuildRsqrtEstimate(SDValue Op);
345     SDValue BuildRsqrtNROneConst(SDValue Op, SDValue Est, unsigned Iterations);
346     SDValue BuildRsqrtNRTwoConst(SDValue Op, SDValue Est, unsigned Iterations);
347     SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
348                                bool DemandHighBits = true);
349     SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
350     SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
351                               SDValue InnerPos, SDValue InnerNeg,
352                               unsigned PosOpcode, unsigned NegOpcode,
353                               SDLoc DL);
354     SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
355     SDValue ReduceLoadWidth(SDNode *N);
356     SDValue ReduceLoadOpStoreWidth(SDNode *N);
357     SDValue TransformFPLoadStorePair(SDNode *N);
358     SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
359     SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
360
361     SDValue GetDemandedBits(SDValue V, const APInt &Mask);
362
363     /// Walk up chain skipping non-aliasing memory nodes,
364     /// looking for aliasing nodes and adding them to the Aliases vector.
365     void GatherAllAliases(SDNode *N, SDValue OriginalChain,
366                           SmallVectorImpl<SDValue> &Aliases);
367
368     /// Return true if there is any possibility that the two addresses overlap.
369     bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
370
371     /// Walk up chain skipping non-aliasing memory nodes, looking for a better
372     /// chain (aliasing node.)
373     SDValue FindBetterChain(SDNode *N, SDValue Chain);
374
375     /// Holds a pointer to an LSBaseSDNode as well as information on where it
376     /// is located in a sequence of memory operations connected by a chain.
377     struct MemOpLink {
378       MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
379       MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
380       // Ptr to the mem node.
381       LSBaseSDNode *MemNode;
382       // Offset from the base ptr.
383       int64_t OffsetFromBase;
384       // What is the sequence number of this mem node.
385       // Lowest mem operand in the DAG starts at zero.
386       unsigned SequenceNum;
387     };
388
389     /// This is a helper function for MergeConsecutiveStores. When the source
390     /// elements of the consecutive stores are all constants or all extracted
391     /// vector elements, try to merge them into one larger store.
392     /// \return True if a merged store was created.
393     bool MergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes,
394                                          EVT MemVT, unsigned NumElem,
395                                          bool IsConstantSrc, bool UseVector);
396
397     /// Merge consecutive store operations into a wide store.
398     /// This optimization uses wide integers or vectors when possible.
399     /// \return True if some memory operations were changed.
400     bool MergeConsecutiveStores(StoreSDNode *N);
401
402     /// \brief Try to transform a truncation where C is a constant:
403     ///     (trunc (and X, C)) -> (and (trunc X), (trunc C))
404     ///
405     /// \p N needs to be a truncation and its first operand an AND. Other
406     /// requirements are checked by the function (e.g. that trunc is
407     /// single-use) and if missed an empty SDValue is returned.
408     SDValue distributeTruncateThroughAnd(SDNode *N);
409
410   public:
411     DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
412         : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
413           OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
414       auto *F = DAG.getMachineFunction().getFunction();
415       ForCodeSize = F->hasFnAttribute(Attribute::OptimizeForSize) ||
416                     F->hasFnAttribute(Attribute::MinSize);
417     }
418
419     /// Runs the dag combiner on all nodes in the work list
420     void Run(CombineLevel AtLevel);
421
422     SelectionDAG &getDAG() const { return DAG; }
423
424     /// Returns a type large enough to hold any valid shift amount - before type
425     /// legalization these can be huge.
426     EVT getShiftAmountTy(EVT LHSTy) {
427       assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
428       if (LHSTy.isVector())
429         return LHSTy;
430       return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy)
431                         : TLI.getPointerTy();
432     }
433
434     /// This method returns true if we are running before type legalization or
435     /// if the specified VT is legal.
436     bool isTypeLegal(const EVT &VT) {
437       if (!LegalTypes) return true;
438       return TLI.isTypeLegal(VT);
439     }
440
441     /// Convenience wrapper around TargetLowering::getSetCCResultType
442     EVT getSetCCResultType(EVT VT) const {
443       return TLI.getSetCCResultType(*DAG.getContext(), VT);
444     }
445   };
446 }
447
448
449 namespace {
450 /// This class is a DAGUpdateListener that removes any deleted
451 /// nodes from the worklist.
452 class WorklistRemover : public SelectionDAG::DAGUpdateListener {
453   DAGCombiner &DC;
454 public:
455   explicit WorklistRemover(DAGCombiner &dc)
456     : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
457
458   void NodeDeleted(SDNode *N, SDNode *E) override {
459     DC.removeFromWorklist(N);
460   }
461 };
462 }
463
464 //===----------------------------------------------------------------------===//
465 //  TargetLowering::DAGCombinerInfo implementation
466 //===----------------------------------------------------------------------===//
467
468 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
469   ((DAGCombiner*)DC)->AddToWorklist(N);
470 }
471
472 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
473   ((DAGCombiner*)DC)->removeFromWorklist(N);
474 }
475
476 SDValue TargetLowering::DAGCombinerInfo::
477 CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) {
478   return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
479 }
480
481 SDValue TargetLowering::DAGCombinerInfo::
482 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
483   return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
484 }
485
486
487 SDValue TargetLowering::DAGCombinerInfo::
488 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
489   return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
490 }
491
492 void TargetLowering::DAGCombinerInfo::
493 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
494   return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
495 }
496
497 //===----------------------------------------------------------------------===//
498 // Helper Functions
499 //===----------------------------------------------------------------------===//
500
501 void DAGCombiner::deleteAndRecombine(SDNode *N) {
502   removeFromWorklist(N);
503
504   // If the operands of this node are only used by the node, they will now be
505   // dead. Make sure to re-visit them and recursively delete dead nodes.
506   for (const SDValue &Op : N->ops())
507     // For an operand generating multiple values, one of the values may
508     // become dead allowing further simplification (e.g. split index
509     // arithmetic from an indexed load).
510     if (Op->hasOneUse() || Op->getNumValues() > 1)
511       AddToWorklist(Op.getNode());
512
513   DAG.DeleteNode(N);
514 }
515
516 /// Return 1 if we can compute the negated form of the specified expression for
517 /// the same cost as the expression itself, or 2 if we can compute the negated
518 /// form more cheaply than the expression itself.
519 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
520                                const TargetLowering &TLI,
521                                const TargetOptions *Options,
522                                unsigned Depth = 0) {
523   // fneg is removable even if it has multiple uses.
524   if (Op.getOpcode() == ISD::FNEG) return 2;
525
526   // Don't allow anything with multiple uses.
527   if (!Op.hasOneUse()) return 0;
528
529   // Don't recurse exponentially.
530   if (Depth > 6) return 0;
531
532   switch (Op.getOpcode()) {
533   default: return false;
534   case ISD::ConstantFP:
535     // Don't invert constant FP values after legalize.  The negated constant
536     // isn't necessarily legal.
537     return LegalOperations ? 0 : 1;
538   case ISD::FADD:
539     // FIXME: determine better conditions for this xform.
540     if (!Options->UnsafeFPMath) return 0;
541
542     // After operation legalization, it might not be legal to create new FSUBs.
543     if (LegalOperations &&
544         !TLI.isOperationLegalOrCustom(ISD::FSUB,  Op.getValueType()))
545       return 0;
546
547     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
548     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
549                                     Options, Depth + 1))
550       return V;
551     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
552     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
553                               Depth + 1);
554   case ISD::FSUB:
555     // We can't turn -(A-B) into B-A when we honor signed zeros.
556     if (!Options->UnsafeFPMath) return 0;
557
558     // fold (fneg (fsub A, B)) -> (fsub B, A)
559     return 1;
560
561   case ISD::FMUL:
562   case ISD::FDIV:
563     if (Options->HonorSignDependentRoundingFPMath()) return 0;
564
565     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
566     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
567                                     Options, Depth + 1))
568       return V;
569
570     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
571                               Depth + 1);
572
573   case ISD::FP_EXTEND:
574   case ISD::FP_ROUND:
575   case ISD::FSIN:
576     return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
577                               Depth + 1);
578   }
579 }
580
581 /// If isNegatibleForFree returns true, return the newly negated expression.
582 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
583                                     bool LegalOperations, unsigned Depth = 0) {
584   const TargetOptions &Options = DAG.getTarget().Options;
585   // fneg is removable even if it has multiple uses.
586   if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
587
588   // Don't allow anything with multiple uses.
589   assert(Op.hasOneUse() && "Unknown reuse!");
590
591   assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
592   switch (Op.getOpcode()) {
593   default: llvm_unreachable("Unknown code");
594   case ISD::ConstantFP: {
595     APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
596     V.changeSign();
597     return DAG.getConstantFP(V, SDLoc(Op), Op.getValueType());
598   }
599   case ISD::FADD:
600     // FIXME: determine better conditions for this xform.
601     assert(Options.UnsafeFPMath);
602
603     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
604     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
605                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
606       return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
607                          GetNegatedExpression(Op.getOperand(0), DAG,
608                                               LegalOperations, Depth+1),
609                          Op.getOperand(1));
610     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
611     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
612                        GetNegatedExpression(Op.getOperand(1), DAG,
613                                             LegalOperations, Depth+1),
614                        Op.getOperand(0));
615   case ISD::FSUB:
616     // We can't turn -(A-B) into B-A when we honor signed zeros.
617     assert(Options.UnsafeFPMath);
618
619     // fold (fneg (fsub 0, B)) -> B
620     if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
621       if (N0CFP->getValueAPF().isZero())
622         return Op.getOperand(1);
623
624     // fold (fneg (fsub A, B)) -> (fsub B, A)
625     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
626                        Op.getOperand(1), Op.getOperand(0));
627
628   case ISD::FMUL:
629   case ISD::FDIV:
630     assert(!Options.HonorSignDependentRoundingFPMath());
631
632     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
633     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
634                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
635       return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
636                          GetNegatedExpression(Op.getOperand(0), DAG,
637                                               LegalOperations, Depth+1),
638                          Op.getOperand(1));
639
640     // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
641     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
642                        Op.getOperand(0),
643                        GetNegatedExpression(Op.getOperand(1), DAG,
644                                             LegalOperations, Depth+1));
645
646   case ISD::FP_EXTEND:
647   case ISD::FSIN:
648     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
649                        GetNegatedExpression(Op.getOperand(0), DAG,
650                                             LegalOperations, Depth+1));
651   case ISD::FP_ROUND:
652       return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
653                          GetNegatedExpression(Op.getOperand(0), DAG,
654                                               LegalOperations, Depth+1),
655                          Op.getOperand(1));
656   }
657 }
658
659 // Return true if this node is a setcc, or is a select_cc
660 // that selects between the target values used for true and false, making it
661 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
662 // the appropriate nodes based on the type of node we are checking. This
663 // simplifies life a bit for the callers.
664 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
665                                     SDValue &CC) const {
666   if (N.getOpcode() == ISD::SETCC) {
667     LHS = N.getOperand(0);
668     RHS = N.getOperand(1);
669     CC  = N.getOperand(2);
670     return true;
671   }
672
673   if (N.getOpcode() != ISD::SELECT_CC ||
674       !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
675       !TLI.isConstFalseVal(N.getOperand(3).getNode()))
676     return false;
677
678   if (TLI.getBooleanContents(N.getValueType()) ==
679       TargetLowering::UndefinedBooleanContent)
680     return false;
681
682   LHS = N.getOperand(0);
683   RHS = N.getOperand(1);
684   CC  = N.getOperand(4);
685   return true;
686 }
687
688 /// Return true if this is a SetCC-equivalent operation with only one use.
689 /// If this is true, it allows the users to invert the operation for free when
690 /// it is profitable to do so.
691 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
692   SDValue N0, N1, N2;
693   if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
694     return true;
695   return false;
696 }
697
698 /// Returns true if N is a BUILD_VECTOR node whose
699 /// elements are all the same constant or undefined.
700 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
701   BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
702   if (!C)
703     return false;
704
705   APInt SplatUndef;
706   unsigned SplatBitSize;
707   bool HasAnyUndefs;
708   EVT EltVT = N->getValueType(0).getVectorElementType();
709   return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
710                              HasAnyUndefs) &&
711           EltVT.getSizeInBits() >= SplatBitSize);
712 }
713
714 // \brief Returns the SDNode if it is a constant integer BuildVector
715 // or constant integer.
716 static SDNode *isConstantIntBuildVectorOrConstantInt(SDValue N) {
717   if (isa<ConstantSDNode>(N))
718     return N.getNode();
719   if (ISD::isBuildVectorOfConstantSDNodes(N.getNode()))
720     return N.getNode();
721   return nullptr;
722 }
723
724 // \brief Returns the SDNode if it is a constant float BuildVector
725 // or constant float.
726 static SDNode *isConstantFPBuildVectorOrConstantFP(SDValue N) {
727   if (isa<ConstantFPSDNode>(N))
728     return N.getNode();
729   if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
730     return N.getNode();
731   return nullptr;
732 }
733
734 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
735 // int.
736 static ConstantSDNode *isConstOrConstSplat(SDValue N) {
737   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
738     return CN;
739
740   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
741     BitVector UndefElements;
742     ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
743
744     // BuildVectors can truncate their operands. Ignore that case here.
745     // FIXME: We blindly ignore splats which include undef which is overly
746     // pessimistic.
747     if (CN && UndefElements.none() &&
748         CN->getValueType(0) == N.getValueType().getScalarType())
749       return CN;
750   }
751
752   return nullptr;
753 }
754
755 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
756 // float.
757 static ConstantFPSDNode *isConstOrConstSplatFP(SDValue N) {
758   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
759     return CN;
760
761   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
762     BitVector UndefElements;
763     ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
764
765     if (CN && UndefElements.none())
766       return CN;
767   }
768
769   return nullptr;
770 }
771
772 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
773                                     SDValue N0, SDValue N1) {
774   EVT VT = N0.getValueType();
775   if (N0.getOpcode() == Opc) {
776     if (SDNode *L = isConstantIntBuildVectorOrConstantInt(N0.getOperand(1))) {
777       if (SDNode *R = isConstantIntBuildVectorOrConstantInt(N1)) {
778         // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
779         if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, L, R))
780           return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
781         return SDValue();
782       }
783       if (N0.hasOneUse()) {
784         // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
785         // use
786         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
787         if (!OpNode.getNode())
788           return SDValue();
789         AddToWorklist(OpNode.getNode());
790         return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
791       }
792     }
793   }
794
795   if (N1.getOpcode() == Opc) {
796     if (SDNode *R = isConstantIntBuildVectorOrConstantInt(N1.getOperand(1))) {
797       if (SDNode *L = isConstantIntBuildVectorOrConstantInt(N0)) {
798         // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
799         if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, R, L))
800           return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
801         return SDValue();
802       }
803       if (N1.hasOneUse()) {
804         // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
805         // use
806         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
807         if (!OpNode.getNode())
808           return SDValue();
809         AddToWorklist(OpNode.getNode());
810         return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
811       }
812     }
813   }
814
815   return SDValue();
816 }
817
818 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
819                                bool AddTo) {
820   assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
821   ++NodesCombined;
822   DEBUG(dbgs() << "\nReplacing.1 ";
823         N->dump(&DAG);
824         dbgs() << "\nWith: ";
825         To[0].getNode()->dump(&DAG);
826         dbgs() << " and " << NumTo-1 << " other values\n");
827   for (unsigned i = 0, e = NumTo; i != e; ++i)
828     assert((!To[i].getNode() ||
829             N->getValueType(i) == To[i].getValueType()) &&
830            "Cannot combine value to value of different type!");
831
832   WorklistRemover DeadNodes(*this);
833   DAG.ReplaceAllUsesWith(N, To);
834   if (AddTo) {
835     // Push the new nodes and any users onto the worklist
836     for (unsigned i = 0, e = NumTo; i != e; ++i) {
837       if (To[i].getNode()) {
838         AddToWorklist(To[i].getNode());
839         AddUsersToWorklist(To[i].getNode());
840       }
841     }
842   }
843
844   // Finally, if the node is now dead, remove it from the graph.  The node
845   // may not be dead if the replacement process recursively simplified to
846   // something else needing this node.
847   if (N->use_empty())
848     deleteAndRecombine(N);
849   return SDValue(N, 0);
850 }
851
852 void DAGCombiner::
853 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
854   // Replace all uses.  If any nodes become isomorphic to other nodes and
855   // are deleted, make sure to remove them from our worklist.
856   WorklistRemover DeadNodes(*this);
857   DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
858
859   // Push the new node and any (possibly new) users onto the worklist.
860   AddToWorklist(TLO.New.getNode());
861   AddUsersToWorklist(TLO.New.getNode());
862
863   // Finally, if the node is now dead, remove it from the graph.  The node
864   // may not be dead if the replacement process recursively simplified to
865   // something else needing this node.
866   if (TLO.Old.getNode()->use_empty())
867     deleteAndRecombine(TLO.Old.getNode());
868 }
869
870 /// Check the specified integer node value to see if it can be simplified or if
871 /// things it uses can be simplified by bit propagation. If so, return true.
872 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
873   TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
874   APInt KnownZero, KnownOne;
875   if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
876     return false;
877
878   // Revisit the node.
879   AddToWorklist(Op.getNode());
880
881   // Replace the old value with the new one.
882   ++NodesCombined;
883   DEBUG(dbgs() << "\nReplacing.2 ";
884         TLO.Old.getNode()->dump(&DAG);
885         dbgs() << "\nWith: ";
886         TLO.New.getNode()->dump(&DAG);
887         dbgs() << '\n');
888
889   CommitTargetLoweringOpt(TLO);
890   return true;
891 }
892
893 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
894   SDLoc dl(Load);
895   EVT VT = Load->getValueType(0);
896   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
897
898   DEBUG(dbgs() << "\nReplacing.9 ";
899         Load->dump(&DAG);
900         dbgs() << "\nWith: ";
901         Trunc.getNode()->dump(&DAG);
902         dbgs() << '\n');
903   WorklistRemover DeadNodes(*this);
904   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
905   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
906   deleteAndRecombine(Load);
907   AddToWorklist(Trunc.getNode());
908 }
909
910 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
911   Replace = false;
912   SDLoc dl(Op);
913   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
914     EVT MemVT = LD->getMemoryVT();
915     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
916       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
917                                                        : ISD::EXTLOAD)
918       : LD->getExtensionType();
919     Replace = true;
920     return DAG.getExtLoad(ExtType, dl, PVT,
921                           LD->getChain(), LD->getBasePtr(),
922                           MemVT, LD->getMemOperand());
923   }
924
925   unsigned Opc = Op.getOpcode();
926   switch (Opc) {
927   default: break;
928   case ISD::AssertSext:
929     return DAG.getNode(ISD::AssertSext, dl, PVT,
930                        SExtPromoteOperand(Op.getOperand(0), PVT),
931                        Op.getOperand(1));
932   case ISD::AssertZext:
933     return DAG.getNode(ISD::AssertZext, dl, PVT,
934                        ZExtPromoteOperand(Op.getOperand(0), PVT),
935                        Op.getOperand(1));
936   case ISD::Constant: {
937     unsigned ExtOpc =
938       Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
939     return DAG.getNode(ExtOpc, dl, PVT, Op);
940   }
941   }
942
943   if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
944     return SDValue();
945   return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
946 }
947
948 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
949   if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
950     return SDValue();
951   EVT OldVT = Op.getValueType();
952   SDLoc dl(Op);
953   bool Replace = false;
954   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
955   if (!NewOp.getNode())
956     return SDValue();
957   AddToWorklist(NewOp.getNode());
958
959   if (Replace)
960     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
961   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
962                      DAG.getValueType(OldVT));
963 }
964
965 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
966   EVT OldVT = Op.getValueType();
967   SDLoc dl(Op);
968   bool Replace = false;
969   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
970   if (!NewOp.getNode())
971     return SDValue();
972   AddToWorklist(NewOp.getNode());
973
974   if (Replace)
975     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
976   return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
977 }
978
979 /// Promote the specified integer binary operation if the target indicates it is
980 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
981 /// i32 since i16 instructions are longer.
982 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
983   if (!LegalOperations)
984     return SDValue();
985
986   EVT VT = Op.getValueType();
987   if (VT.isVector() || !VT.isInteger())
988     return SDValue();
989
990   // If operation type is 'undesirable', e.g. i16 on x86, consider
991   // promoting it.
992   unsigned Opc = Op.getOpcode();
993   if (TLI.isTypeDesirableForOp(Opc, VT))
994     return SDValue();
995
996   EVT PVT = VT;
997   // Consult target whether it is a good idea to promote this operation and
998   // what's the right type to promote it to.
999   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1000     assert(PVT != VT && "Don't know what type to promote to!");
1001
1002     bool Replace0 = false;
1003     SDValue N0 = Op.getOperand(0);
1004     SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
1005     if (!NN0.getNode())
1006       return SDValue();
1007
1008     bool Replace1 = false;
1009     SDValue N1 = Op.getOperand(1);
1010     SDValue NN1;
1011     if (N0 == N1)
1012       NN1 = NN0;
1013     else {
1014       NN1 = PromoteOperand(N1, PVT, Replace1);
1015       if (!NN1.getNode())
1016         return SDValue();
1017     }
1018
1019     AddToWorklist(NN0.getNode());
1020     if (NN1.getNode())
1021       AddToWorklist(NN1.getNode());
1022
1023     if (Replace0)
1024       ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
1025     if (Replace1)
1026       ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
1027
1028     DEBUG(dbgs() << "\nPromoting ";
1029           Op.getNode()->dump(&DAG));
1030     SDLoc dl(Op);
1031     return DAG.getNode(ISD::TRUNCATE, dl, VT,
1032                        DAG.getNode(Opc, dl, PVT, NN0, NN1));
1033   }
1034   return SDValue();
1035 }
1036
1037 /// Promote the specified integer shift operation if the target indicates it is
1038 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1039 /// i32 since i16 instructions are longer.
1040 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
1041   if (!LegalOperations)
1042     return SDValue();
1043
1044   EVT VT = Op.getValueType();
1045   if (VT.isVector() || !VT.isInteger())
1046     return SDValue();
1047
1048   // If operation type is 'undesirable', e.g. i16 on x86, consider
1049   // promoting it.
1050   unsigned Opc = Op.getOpcode();
1051   if (TLI.isTypeDesirableForOp(Opc, VT))
1052     return SDValue();
1053
1054   EVT PVT = VT;
1055   // Consult target whether it is a good idea to promote this operation and
1056   // what's the right type to promote it to.
1057   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1058     assert(PVT != VT && "Don't know what type to promote to!");
1059
1060     bool Replace = false;
1061     SDValue N0 = Op.getOperand(0);
1062     if (Opc == ISD::SRA)
1063       N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
1064     else if (Opc == ISD::SRL)
1065       N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
1066     else
1067       N0 = PromoteOperand(N0, PVT, Replace);
1068     if (!N0.getNode())
1069       return SDValue();
1070
1071     AddToWorklist(N0.getNode());
1072     if (Replace)
1073       ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1074
1075     DEBUG(dbgs() << "\nPromoting ";
1076           Op.getNode()->dump(&DAG));
1077     SDLoc dl(Op);
1078     return DAG.getNode(ISD::TRUNCATE, dl, VT,
1079                        DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
1080   }
1081   return SDValue();
1082 }
1083
1084 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1085   if (!LegalOperations)
1086     return SDValue();
1087
1088   EVT VT = Op.getValueType();
1089   if (VT.isVector() || !VT.isInteger())
1090     return SDValue();
1091
1092   // If operation type is 'undesirable', e.g. i16 on x86, consider
1093   // promoting it.
1094   unsigned Opc = Op.getOpcode();
1095   if (TLI.isTypeDesirableForOp(Opc, VT))
1096     return SDValue();
1097
1098   EVT PVT = VT;
1099   // Consult target whether it is a good idea to promote this operation and
1100   // what's the right type to promote it to.
1101   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1102     assert(PVT != VT && "Don't know what type to promote to!");
1103     // fold (aext (aext x)) -> (aext x)
1104     // fold (aext (zext x)) -> (zext x)
1105     // fold (aext (sext x)) -> (sext x)
1106     DEBUG(dbgs() << "\nPromoting ";
1107           Op.getNode()->dump(&DAG));
1108     return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1109   }
1110   return SDValue();
1111 }
1112
1113 bool DAGCombiner::PromoteLoad(SDValue Op) {
1114   if (!LegalOperations)
1115     return false;
1116
1117   EVT VT = Op.getValueType();
1118   if (VT.isVector() || !VT.isInteger())
1119     return false;
1120
1121   // If operation type is 'undesirable', e.g. i16 on x86, consider
1122   // promoting it.
1123   unsigned Opc = Op.getOpcode();
1124   if (TLI.isTypeDesirableForOp(Opc, VT))
1125     return false;
1126
1127   EVT PVT = VT;
1128   // Consult target whether it is a good idea to promote this operation and
1129   // what's the right type to promote it to.
1130   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1131     assert(PVT != VT && "Don't know what type to promote to!");
1132
1133     SDLoc dl(Op);
1134     SDNode *N = Op.getNode();
1135     LoadSDNode *LD = cast<LoadSDNode>(N);
1136     EVT MemVT = LD->getMemoryVT();
1137     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1138       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
1139                                                        : ISD::EXTLOAD)
1140       : LD->getExtensionType();
1141     SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1142                                    LD->getChain(), LD->getBasePtr(),
1143                                    MemVT, LD->getMemOperand());
1144     SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1145
1146     DEBUG(dbgs() << "\nPromoting ";
1147           N->dump(&DAG);
1148           dbgs() << "\nTo: ";
1149           Result.getNode()->dump(&DAG);
1150           dbgs() << '\n');
1151     WorklistRemover DeadNodes(*this);
1152     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1153     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1154     deleteAndRecombine(N);
1155     AddToWorklist(Result.getNode());
1156     return true;
1157   }
1158   return false;
1159 }
1160
1161 /// \brief Recursively delete a node which has no uses and any operands for
1162 /// which it is the only use.
1163 ///
1164 /// Note that this both deletes the nodes and removes them from the worklist.
1165 /// It also adds any nodes who have had a user deleted to the worklist as they
1166 /// may now have only one use and subject to other combines.
1167 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1168   if (!N->use_empty())
1169     return false;
1170
1171   SmallSetVector<SDNode *, 16> Nodes;
1172   Nodes.insert(N);
1173   do {
1174     N = Nodes.pop_back_val();
1175     if (!N)
1176       continue;
1177
1178     if (N->use_empty()) {
1179       for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1180         Nodes.insert(N->getOperand(i).getNode());
1181
1182       removeFromWorklist(N);
1183       DAG.DeleteNode(N);
1184     } else {
1185       AddToWorklist(N);
1186     }
1187   } while (!Nodes.empty());
1188   return true;
1189 }
1190
1191 //===----------------------------------------------------------------------===//
1192 //  Main DAG Combiner implementation
1193 //===----------------------------------------------------------------------===//
1194
1195 void DAGCombiner::Run(CombineLevel AtLevel) {
1196   // set the instance variables, so that the various visit routines may use it.
1197   Level = AtLevel;
1198   LegalOperations = Level >= AfterLegalizeVectorOps;
1199   LegalTypes = Level >= AfterLegalizeTypes;
1200
1201   // Add all the dag nodes to the worklist.
1202   for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1203        E = DAG.allnodes_end(); I != E; ++I)
1204     AddToWorklist(I);
1205
1206   // Create a dummy node (which is not added to allnodes), that adds a reference
1207   // to the root node, preventing it from being deleted, and tracking any
1208   // changes of the root.
1209   HandleSDNode Dummy(DAG.getRoot());
1210
1211   // while the worklist isn't empty, find a node and
1212   // try and combine it.
1213   while (!WorklistMap.empty()) {
1214     SDNode *N;
1215     // The Worklist holds the SDNodes in order, but it may contain null entries.
1216     do {
1217       N = Worklist.pop_back_val();
1218     } while (!N);
1219
1220     bool GoodWorklistEntry = WorklistMap.erase(N);
1221     (void)GoodWorklistEntry;
1222     assert(GoodWorklistEntry &&
1223            "Found a worklist entry without a corresponding map entry!");
1224
1225     // If N has no uses, it is dead.  Make sure to revisit all N's operands once
1226     // N is deleted from the DAG, since they too may now be dead or may have a
1227     // reduced number of uses, allowing other xforms.
1228     if (recursivelyDeleteUnusedNodes(N))
1229       continue;
1230
1231     WorklistRemover DeadNodes(*this);
1232
1233     // If this combine is running after legalizing the DAG, re-legalize any
1234     // nodes pulled off the worklist.
1235     if (Level == AfterLegalizeDAG) {
1236       SmallSetVector<SDNode *, 16> UpdatedNodes;
1237       bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1238
1239       for (SDNode *LN : UpdatedNodes) {
1240         AddToWorklist(LN);
1241         AddUsersToWorklist(LN);
1242       }
1243       if (!NIsValid)
1244         continue;
1245     }
1246
1247     DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1248
1249     // Add any operands of the new node which have not yet been combined to the
1250     // worklist as well. Because the worklist uniques things already, this
1251     // won't repeatedly process the same operand.
1252     CombinedNodes.insert(N);
1253     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1254       if (!CombinedNodes.count(N->getOperand(i).getNode()))
1255         AddToWorklist(N->getOperand(i).getNode());
1256
1257     SDValue RV = combine(N);
1258
1259     if (!RV.getNode())
1260       continue;
1261
1262     ++NodesCombined;
1263
1264     // If we get back the same node we passed in, rather than a new node or
1265     // zero, we know that the node must have defined multiple values and
1266     // CombineTo was used.  Since CombineTo takes care of the worklist
1267     // mechanics for us, we have no work to do in this case.
1268     if (RV.getNode() == N)
1269       continue;
1270
1271     assert(N->getOpcode() != ISD::DELETED_NODE &&
1272            RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1273            "Node was deleted but visit returned new node!");
1274
1275     DEBUG(dbgs() << " ... into: ";
1276           RV.getNode()->dump(&DAG));
1277
1278     // Transfer debug value.
1279     DAG.TransferDbgValues(SDValue(N, 0), RV);
1280     if (N->getNumValues() == RV.getNode()->getNumValues())
1281       DAG.ReplaceAllUsesWith(N, RV.getNode());
1282     else {
1283       assert(N->getValueType(0) == RV.getValueType() &&
1284              N->getNumValues() == 1 && "Type mismatch");
1285       SDValue OpV = RV;
1286       DAG.ReplaceAllUsesWith(N, &OpV);
1287     }
1288
1289     // Push the new node and any users onto the worklist
1290     AddToWorklist(RV.getNode());
1291     AddUsersToWorklist(RV.getNode());
1292
1293     // Finally, if the node is now dead, remove it from the graph.  The node
1294     // may not be dead if the replacement process recursively simplified to
1295     // something else needing this node. This will also take care of adding any
1296     // operands which have lost a user to the worklist.
1297     recursivelyDeleteUnusedNodes(N);
1298   }
1299
1300   // If the root changed (e.g. it was a dead load, update the root).
1301   DAG.setRoot(Dummy.getValue());
1302   DAG.RemoveDeadNodes();
1303 }
1304
1305 SDValue DAGCombiner::visit(SDNode *N) {
1306   switch (N->getOpcode()) {
1307   default: break;
1308   case ISD::TokenFactor:        return visitTokenFactor(N);
1309   case ISD::MERGE_VALUES:       return visitMERGE_VALUES(N);
1310   case ISD::ADD:                return visitADD(N);
1311   case ISD::SUB:                return visitSUB(N);
1312   case ISD::ADDC:               return visitADDC(N);
1313   case ISD::SUBC:               return visitSUBC(N);
1314   case ISD::ADDE:               return visitADDE(N);
1315   case ISD::SUBE:               return visitSUBE(N);
1316   case ISD::MUL:                return visitMUL(N);
1317   case ISD::SDIV:               return visitSDIV(N);
1318   case ISD::UDIV:               return visitUDIV(N);
1319   case ISD::SREM:               return visitSREM(N);
1320   case ISD::UREM:               return visitUREM(N);
1321   case ISD::MULHU:              return visitMULHU(N);
1322   case ISD::MULHS:              return visitMULHS(N);
1323   case ISD::SMUL_LOHI:          return visitSMUL_LOHI(N);
1324   case ISD::UMUL_LOHI:          return visitUMUL_LOHI(N);
1325   case ISD::SMULO:              return visitSMULO(N);
1326   case ISD::UMULO:              return visitUMULO(N);
1327   case ISD::SDIVREM:            return visitSDIVREM(N);
1328   case ISD::UDIVREM:            return visitUDIVREM(N);
1329   case ISD::AND:                return visitAND(N);
1330   case ISD::OR:                 return visitOR(N);
1331   case ISD::XOR:                return visitXOR(N);
1332   case ISD::SHL:                return visitSHL(N);
1333   case ISD::SRA:                return visitSRA(N);
1334   case ISD::SRL:                return visitSRL(N);
1335   case ISD::ROTR:
1336   case ISD::ROTL:               return visitRotate(N);
1337   case ISD::CTLZ:               return visitCTLZ(N);
1338   case ISD::CTLZ_ZERO_UNDEF:    return visitCTLZ_ZERO_UNDEF(N);
1339   case ISD::CTTZ:               return visitCTTZ(N);
1340   case ISD::CTTZ_ZERO_UNDEF:    return visitCTTZ_ZERO_UNDEF(N);
1341   case ISD::CTPOP:              return visitCTPOP(N);
1342   case ISD::SELECT:             return visitSELECT(N);
1343   case ISD::VSELECT:            return visitVSELECT(N);
1344   case ISD::SELECT_CC:          return visitSELECT_CC(N);
1345   case ISD::SETCC:              return visitSETCC(N);
1346   case ISD::SIGN_EXTEND:        return visitSIGN_EXTEND(N);
1347   case ISD::ZERO_EXTEND:        return visitZERO_EXTEND(N);
1348   case ISD::ANY_EXTEND:         return visitANY_EXTEND(N);
1349   case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
1350   case ISD::TRUNCATE:           return visitTRUNCATE(N);
1351   case ISD::BITCAST:            return visitBITCAST(N);
1352   case ISD::BUILD_PAIR:         return visitBUILD_PAIR(N);
1353   case ISD::FADD:               return visitFADD(N);
1354   case ISD::FSUB:               return visitFSUB(N);
1355   case ISD::FMUL:               return visitFMUL(N);
1356   case ISD::FMA:                return visitFMA(N);
1357   case ISD::FDIV:               return visitFDIV(N);
1358   case ISD::FREM:               return visitFREM(N);
1359   case ISD::FSQRT:              return visitFSQRT(N);
1360   case ISD::FCOPYSIGN:          return visitFCOPYSIGN(N);
1361   case ISD::SINT_TO_FP:         return visitSINT_TO_FP(N);
1362   case ISD::UINT_TO_FP:         return visitUINT_TO_FP(N);
1363   case ISD::FP_TO_SINT:         return visitFP_TO_SINT(N);
1364   case ISD::FP_TO_UINT:         return visitFP_TO_UINT(N);
1365   case ISD::FP_ROUND:           return visitFP_ROUND(N);
1366   case ISD::FP_ROUND_INREG:     return visitFP_ROUND_INREG(N);
1367   case ISD::FP_EXTEND:          return visitFP_EXTEND(N);
1368   case ISD::FNEG:               return visitFNEG(N);
1369   case ISD::FABS:               return visitFABS(N);
1370   case ISD::FFLOOR:             return visitFFLOOR(N);
1371   case ISD::FMINNUM:            return visitFMINNUM(N);
1372   case ISD::FMAXNUM:            return visitFMAXNUM(N);
1373   case ISD::FCEIL:              return visitFCEIL(N);
1374   case ISD::FTRUNC:             return visitFTRUNC(N);
1375   case ISD::BRCOND:             return visitBRCOND(N);
1376   case ISD::BR_CC:              return visitBR_CC(N);
1377   case ISD::LOAD:               return visitLOAD(N);
1378   case ISD::STORE:              return visitSTORE(N);
1379   case ISD::INSERT_VECTOR_ELT:  return visitINSERT_VECTOR_ELT(N);
1380   case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1381   case ISD::BUILD_VECTOR:       return visitBUILD_VECTOR(N);
1382   case ISD::CONCAT_VECTORS:     return visitCONCAT_VECTORS(N);
1383   case ISD::EXTRACT_SUBVECTOR:  return visitEXTRACT_SUBVECTOR(N);
1384   case ISD::VECTOR_SHUFFLE:     return visitVECTOR_SHUFFLE(N);
1385   case ISD::SCALAR_TO_VECTOR:   return visitSCALAR_TO_VECTOR(N);
1386   case ISD::INSERT_SUBVECTOR:   return visitINSERT_SUBVECTOR(N);
1387   case ISD::MGATHER:            return visitMGATHER(N);
1388   case ISD::MLOAD:              return visitMLOAD(N);
1389   case ISD::MSCATTER:           return visitMSCATTER(N);
1390   case ISD::MSTORE:             return visitMSTORE(N);
1391   case ISD::FP_TO_FP16:         return visitFP_TO_FP16(N);
1392   }
1393   return SDValue();
1394 }
1395
1396 SDValue DAGCombiner::combine(SDNode *N) {
1397   SDValue RV = visit(N);
1398
1399   // If nothing happened, try a target-specific DAG combine.
1400   if (!RV.getNode()) {
1401     assert(N->getOpcode() != ISD::DELETED_NODE &&
1402            "Node was deleted but visit returned NULL!");
1403
1404     if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1405         TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1406
1407       // Expose the DAG combiner to the target combiner impls.
1408       TargetLowering::DAGCombinerInfo
1409         DagCombineInfo(DAG, Level, false, this);
1410
1411       RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1412     }
1413   }
1414
1415   // If nothing happened still, try promoting the operation.
1416   if (!RV.getNode()) {
1417     switch (N->getOpcode()) {
1418     default: break;
1419     case ISD::ADD:
1420     case ISD::SUB:
1421     case ISD::MUL:
1422     case ISD::AND:
1423     case ISD::OR:
1424     case ISD::XOR:
1425       RV = PromoteIntBinOp(SDValue(N, 0));
1426       break;
1427     case ISD::SHL:
1428     case ISD::SRA:
1429     case ISD::SRL:
1430       RV = PromoteIntShiftOp(SDValue(N, 0));
1431       break;
1432     case ISD::SIGN_EXTEND:
1433     case ISD::ZERO_EXTEND:
1434     case ISD::ANY_EXTEND:
1435       RV = PromoteExtend(SDValue(N, 0));
1436       break;
1437     case ISD::LOAD:
1438       if (PromoteLoad(SDValue(N, 0)))
1439         RV = SDValue(N, 0);
1440       break;
1441     }
1442   }
1443
1444   // If N is a commutative binary node, try commuting it to enable more
1445   // sdisel CSE.
1446   if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1447       N->getNumValues() == 1) {
1448     SDValue N0 = N->getOperand(0);
1449     SDValue N1 = N->getOperand(1);
1450
1451     // Constant operands are canonicalized to RHS.
1452     if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1453       SDValue Ops[] = {N1, N0};
1454       SDNode *CSENode;
1455       if (const BinaryWithFlagsSDNode *BinNode =
1456               dyn_cast<BinaryWithFlagsSDNode>(N)) {
1457         CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops,
1458                                       BinNode->Flags.hasNoUnsignedWrap(),
1459                                       BinNode->Flags.hasNoSignedWrap(),
1460                                       BinNode->Flags.hasExact());
1461       } else {
1462         CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops);
1463       }
1464       if (CSENode)
1465         return SDValue(CSENode, 0);
1466     }
1467   }
1468
1469   return RV;
1470 }
1471
1472 /// Given a node, return its input chain if it has one, otherwise return a null
1473 /// sd operand.
1474 static SDValue getInputChainForNode(SDNode *N) {
1475   if (unsigned NumOps = N->getNumOperands()) {
1476     if (N->getOperand(0).getValueType() == MVT::Other)
1477       return N->getOperand(0);
1478     if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1479       return N->getOperand(NumOps-1);
1480     for (unsigned i = 1; i < NumOps-1; ++i)
1481       if (N->getOperand(i).getValueType() == MVT::Other)
1482         return N->getOperand(i);
1483   }
1484   return SDValue();
1485 }
1486
1487 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1488   // If N has two operands, where one has an input chain equal to the other,
1489   // the 'other' chain is redundant.
1490   if (N->getNumOperands() == 2) {
1491     if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1492       return N->getOperand(0);
1493     if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1494       return N->getOperand(1);
1495   }
1496
1497   SmallVector<SDNode *, 8> TFs;     // List of token factors to visit.
1498   SmallVector<SDValue, 8> Ops;    // Ops for replacing token factor.
1499   SmallPtrSet<SDNode*, 16> SeenOps;
1500   bool Changed = false;             // If we should replace this token factor.
1501
1502   // Start out with this token factor.
1503   TFs.push_back(N);
1504
1505   // Iterate through token factors.  The TFs grows when new token factors are
1506   // encountered.
1507   for (unsigned i = 0; i < TFs.size(); ++i) {
1508     SDNode *TF = TFs[i];
1509
1510     // Check each of the operands.
1511     for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1512       SDValue Op = TF->getOperand(i);
1513
1514       switch (Op.getOpcode()) {
1515       case ISD::EntryToken:
1516         // Entry tokens don't need to be added to the list. They are
1517         // redundant.
1518         Changed = true;
1519         break;
1520
1521       case ISD::TokenFactor:
1522         if (Op.hasOneUse() &&
1523             std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1524           // Queue up for processing.
1525           TFs.push_back(Op.getNode());
1526           // Clean up in case the token factor is removed.
1527           AddToWorklist(Op.getNode());
1528           Changed = true;
1529           break;
1530         }
1531         // Fall thru
1532
1533       default:
1534         // Only add if it isn't already in the list.
1535         if (SeenOps.insert(Op.getNode()).second)
1536           Ops.push_back(Op);
1537         else
1538           Changed = true;
1539         break;
1540       }
1541     }
1542   }
1543
1544   SDValue Result;
1545
1546   // If we've changed things around then replace token factor.
1547   if (Changed) {
1548     if (Ops.empty()) {
1549       // The entry token is the only possible outcome.
1550       Result = DAG.getEntryNode();
1551     } else {
1552       // New and improved token factor.
1553       Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1554     }
1555
1556     // Add users to worklist if AA is enabled, since it may introduce
1557     // a lot of new chained token factors while removing memory deps.
1558     bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
1559       : DAG.getSubtarget().useAA();
1560     return CombineTo(N, Result, UseAA /*add to worklist*/);
1561   }
1562
1563   return Result;
1564 }
1565
1566 /// MERGE_VALUES can always be eliminated.
1567 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1568   WorklistRemover DeadNodes(*this);
1569   // Replacing results may cause a different MERGE_VALUES to suddenly
1570   // be CSE'd with N, and carry its uses with it. Iterate until no
1571   // uses remain, to ensure that the node can be safely deleted.
1572   // First add the users of this node to the work list so that they
1573   // can be tried again once they have new operands.
1574   AddUsersToWorklist(N);
1575   do {
1576     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1577       DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1578   } while (!N->use_empty());
1579   deleteAndRecombine(N);
1580   return SDValue(N, 0);   // Return N so it doesn't get rechecked!
1581 }
1582
1583 static bool isNullConstant(SDValue V) {
1584   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
1585   return Const != nullptr && Const->isNullValue();
1586 }
1587
1588 SDValue DAGCombiner::visitADD(SDNode *N) {
1589   SDValue N0 = N->getOperand(0);
1590   SDValue N1 = N->getOperand(1);
1591   EVT VT = N0.getValueType();
1592
1593   // fold vector ops
1594   if (VT.isVector()) {
1595     if (SDValue FoldedVOp = SimplifyVBinOp(N))
1596       return FoldedVOp;
1597
1598     // fold (add x, 0) -> x, vector edition
1599     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1600       return N0;
1601     if (ISD::isBuildVectorAllZeros(N0.getNode()))
1602       return N1;
1603   }
1604
1605   // fold (add x, undef) -> undef
1606   if (N0.getOpcode() == ISD::UNDEF)
1607     return N0;
1608   if (N1.getOpcode() == ISD::UNDEF)
1609     return N1;
1610   // fold (add c1, c2) -> c1+c2
1611   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1612   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1613   if (N0C && N1C)
1614     return DAG.FoldConstantArithmetic(ISD::ADD, SDLoc(N), VT, N0C, N1C);
1615   // canonicalize constant to RHS
1616   if (isConstantIntBuildVectorOrConstantInt(N0) &&
1617      !isConstantIntBuildVectorOrConstantInt(N1))
1618     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1619   // fold (add x, 0) -> x
1620   if (isNullConstant(N1))
1621     return N0;
1622   // fold (add Sym, c) -> Sym+c
1623   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1624     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1625         GA->getOpcode() == ISD::GlobalAddress)
1626       return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1627                                   GA->getOffset() +
1628                                     (uint64_t)N1C->getSExtValue());
1629   // fold ((c1-A)+c2) -> (c1+c2)-A
1630   if (N1C && N0.getOpcode() == ISD::SUB)
1631     if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0))) {
1632       SDLoc DL(N);
1633       return DAG.getNode(ISD::SUB, DL, VT,
1634                          DAG.getConstant(N1C->getAPIntValue()+
1635                                          N0C->getAPIntValue(), DL, VT),
1636                          N0.getOperand(1));
1637     }
1638   // reassociate add
1639   if (SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1))
1640     return RADD;
1641   // fold ((0-A) + B) -> B-A
1642   if (N0.getOpcode() == ISD::SUB && isNullConstant(N0.getOperand(0)))
1643     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1644   // fold (A + (0-B)) -> A-B
1645   if (N1.getOpcode() == ISD::SUB && isNullConstant(N1.getOperand(0)))
1646     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1647   // fold (A+(B-A)) -> B
1648   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1649     return N1.getOperand(0);
1650   // fold ((B-A)+A) -> B
1651   if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1652     return N0.getOperand(0);
1653   // fold (A+(B-(A+C))) to (B-C)
1654   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1655       N0 == N1.getOperand(1).getOperand(0))
1656     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1657                        N1.getOperand(1).getOperand(1));
1658   // fold (A+(B-(C+A))) to (B-C)
1659   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1660       N0 == N1.getOperand(1).getOperand(1))
1661     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1662                        N1.getOperand(1).getOperand(0));
1663   // fold (A+((B-A)+or-C)) to (B+or-C)
1664   if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1665       N1.getOperand(0).getOpcode() == ISD::SUB &&
1666       N0 == N1.getOperand(0).getOperand(1))
1667     return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1668                        N1.getOperand(0).getOperand(0), N1.getOperand(1));
1669
1670   // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1671   if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1672     SDValue N00 = N0.getOperand(0);
1673     SDValue N01 = N0.getOperand(1);
1674     SDValue N10 = N1.getOperand(0);
1675     SDValue N11 = N1.getOperand(1);
1676
1677     if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1678       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1679                          DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1680                          DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1681   }
1682
1683   if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1684     return SDValue(N, 0);
1685
1686   // fold (a+b) -> (a|b) iff a and b share no bits.
1687   if (VT.isInteger() && !VT.isVector()) {
1688     APInt LHSZero, LHSOne;
1689     APInt RHSZero, RHSOne;
1690     DAG.computeKnownBits(N0, LHSZero, LHSOne);
1691
1692     if (LHSZero.getBoolValue()) {
1693       DAG.computeKnownBits(N1, RHSZero, RHSOne);
1694
1695       // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1696       // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1697       if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1698         if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1699           return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1700       }
1701     }
1702   }
1703
1704   // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1705   if (N1.getOpcode() == ISD::SHL && N1.getOperand(0).getOpcode() == ISD::SUB &&
1706       isNullConstant(N1.getOperand(0).getOperand(0)))
1707     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1708                        DAG.getNode(ISD::SHL, SDLoc(N), VT,
1709                                    N1.getOperand(0).getOperand(1),
1710                                    N1.getOperand(1)));
1711   if (N0.getOpcode() == ISD::SHL && N0.getOperand(0).getOpcode() == ISD::SUB &&
1712       isNullConstant(N0.getOperand(0).getOperand(0)))
1713     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1714                        DAG.getNode(ISD::SHL, SDLoc(N), VT,
1715                                    N0.getOperand(0).getOperand(1),
1716                                    N0.getOperand(1)));
1717
1718   if (N1.getOpcode() == ISD::AND) {
1719     SDValue AndOp0 = N1.getOperand(0);
1720     ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1721     unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1722     unsigned DestBits = VT.getScalarType().getSizeInBits();
1723
1724     // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1725     // and similar xforms where the inner op is either ~0 or 0.
1726     if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1727       SDLoc DL(N);
1728       return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1729     }
1730   }
1731
1732   // add (sext i1), X -> sub X, (zext i1)
1733   if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1734       N0.getOperand(0).getValueType() == MVT::i1 &&
1735       !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1736     SDLoc DL(N);
1737     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1738     return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1739   }
1740
1741   // add X, (sextinreg Y i1) -> sub X, (and Y 1)
1742   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1743     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1744     if (TN->getVT() == MVT::i1) {
1745       SDLoc DL(N);
1746       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1747                                  DAG.getConstant(1, DL, VT));
1748       return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
1749     }
1750   }
1751
1752   return SDValue();
1753 }
1754
1755 SDValue DAGCombiner::visitADDC(SDNode *N) {
1756   SDValue N0 = N->getOperand(0);
1757   SDValue N1 = N->getOperand(1);
1758   EVT VT = N0.getValueType();
1759
1760   // If the flag result is dead, turn this into an ADD.
1761   if (!N->hasAnyUseOfValue(1))
1762     return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1763                      DAG.getNode(ISD::CARRY_FALSE,
1764                                  SDLoc(N), MVT::Glue));
1765
1766   // canonicalize constant to RHS.
1767   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1768   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1769   if (N0C && !N1C)
1770     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1771
1772   // fold (addc x, 0) -> x + no carry out
1773   if (isNullConstant(N1))
1774     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1775                                         SDLoc(N), MVT::Glue));
1776
1777   // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1778   APInt LHSZero, LHSOne;
1779   APInt RHSZero, RHSOne;
1780   DAG.computeKnownBits(N0, LHSZero, LHSOne);
1781
1782   if (LHSZero.getBoolValue()) {
1783     DAG.computeKnownBits(N1, RHSZero, RHSOne);
1784
1785     // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1786     // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1787     if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1788       return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1789                        DAG.getNode(ISD::CARRY_FALSE,
1790                                    SDLoc(N), MVT::Glue));
1791   }
1792
1793   return SDValue();
1794 }
1795
1796 SDValue DAGCombiner::visitADDE(SDNode *N) {
1797   SDValue N0 = N->getOperand(0);
1798   SDValue N1 = N->getOperand(1);
1799   SDValue CarryIn = N->getOperand(2);
1800
1801   // canonicalize constant to RHS
1802   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1803   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1804   if (N0C && !N1C)
1805     return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1806                        N1, N0, CarryIn);
1807
1808   // fold (adde x, y, false) -> (addc x, y)
1809   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1810     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1811
1812   return SDValue();
1813 }
1814
1815 // Since it may not be valid to emit a fold to zero for vector initializers
1816 // check if we can before folding.
1817 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1818                              SelectionDAG &DAG,
1819                              bool LegalOperations, bool LegalTypes) {
1820   if (!VT.isVector())
1821     return DAG.getConstant(0, DL, VT);
1822   if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1823     return DAG.getConstant(0, DL, VT);
1824   return SDValue();
1825 }
1826
1827 SDValue DAGCombiner::visitSUB(SDNode *N) {
1828   SDValue N0 = N->getOperand(0);
1829   SDValue N1 = N->getOperand(1);
1830   EVT VT = N0.getValueType();
1831
1832   // fold vector ops
1833   if (VT.isVector()) {
1834     if (SDValue FoldedVOp = SimplifyVBinOp(N))
1835       return FoldedVOp;
1836
1837     // fold (sub x, 0) -> x, vector edition
1838     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1839       return N0;
1840   }
1841
1842   // fold (sub x, x) -> 0
1843   // FIXME: Refactor this and xor and other similar operations together.
1844   if (N0 == N1)
1845     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1846   // fold (sub c1, c2) -> c1-c2
1847   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1848   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1849   if (N0C && N1C)
1850     return DAG.FoldConstantArithmetic(ISD::SUB, SDLoc(N), VT, N0C, N1C);
1851   // fold (sub x, c) -> (add x, -c)
1852   if (N1C) {
1853     SDLoc DL(N);
1854     return DAG.getNode(ISD::ADD, DL, VT, N0,
1855                        DAG.getConstant(-N1C->getAPIntValue(), DL, VT));
1856   }
1857   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1858   if (N0C && N0C->isAllOnesValue())
1859     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1860   // fold A-(A-B) -> B
1861   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1862     return N1.getOperand(1);
1863   // fold (A+B)-A -> B
1864   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1865     return N0.getOperand(1);
1866   // fold (A+B)-B -> A
1867   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1868     return N0.getOperand(0);
1869   // fold C2-(A+C1) -> (C2-C1)-A
1870   ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1871     dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1872   if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1873     SDLoc DL(N);
1874     SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1875                                    DL, VT);
1876     return DAG.getNode(ISD::SUB, DL, VT, NewC,
1877                        N1.getOperand(0));
1878   }
1879   // fold ((A+(B+or-C))-B) -> A+or-C
1880   if (N0.getOpcode() == ISD::ADD &&
1881       (N0.getOperand(1).getOpcode() == ISD::SUB ||
1882        N0.getOperand(1).getOpcode() == ISD::ADD) &&
1883       N0.getOperand(1).getOperand(0) == N1)
1884     return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1885                        N0.getOperand(0), N0.getOperand(1).getOperand(1));
1886   // fold ((A+(C+B))-B) -> A+C
1887   if (N0.getOpcode() == ISD::ADD &&
1888       N0.getOperand(1).getOpcode() == ISD::ADD &&
1889       N0.getOperand(1).getOperand(1) == N1)
1890     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1891                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1892   // fold ((A-(B-C))-C) -> A-B
1893   if (N0.getOpcode() == ISD::SUB &&
1894       N0.getOperand(1).getOpcode() == ISD::SUB &&
1895       N0.getOperand(1).getOperand(1) == N1)
1896     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1897                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1898
1899   // If either operand of a sub is undef, the result is undef
1900   if (N0.getOpcode() == ISD::UNDEF)
1901     return N0;
1902   if (N1.getOpcode() == ISD::UNDEF)
1903     return N1;
1904
1905   // If the relocation model supports it, consider symbol offsets.
1906   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1907     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1908       // fold (sub Sym, c) -> Sym-c
1909       if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1910         return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1911                                     GA->getOffset() -
1912                                       (uint64_t)N1C->getSExtValue());
1913       // fold (sub Sym+c1, Sym+c2) -> c1-c2
1914       if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1915         if (GA->getGlobal() == GB->getGlobal())
1916           return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1917                                  SDLoc(N), VT);
1918     }
1919
1920   // sub X, (sextinreg Y i1) -> add X, (and Y 1)
1921   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1922     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1923     if (TN->getVT() == MVT::i1) {
1924       SDLoc DL(N);
1925       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1926                                  DAG.getConstant(1, DL, VT));
1927       return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
1928     }
1929   }
1930
1931   return SDValue();
1932 }
1933
1934 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1935   SDValue N0 = N->getOperand(0);
1936   SDValue N1 = N->getOperand(1);
1937   EVT VT = N0.getValueType();
1938
1939   // If the flag result is dead, turn this into an SUB.
1940   if (!N->hasAnyUseOfValue(1))
1941     return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1942                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1943                                  MVT::Glue));
1944
1945   // fold (subc x, x) -> 0 + no borrow
1946   if (N0 == N1) {
1947     SDLoc DL(N);
1948     return CombineTo(N, DAG.getConstant(0, DL, VT),
1949                      DAG.getNode(ISD::CARRY_FALSE, DL,
1950                                  MVT::Glue));
1951   }
1952
1953   // fold (subc x, 0) -> x + no borrow
1954   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1955   if (isNullConstant(N1))
1956     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1957                                         MVT::Glue));
1958
1959   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1960   if (N0C && N0C->isAllOnesValue())
1961     return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1962                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1963                                  MVT::Glue));
1964
1965   return SDValue();
1966 }
1967
1968 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1969   SDValue N0 = N->getOperand(0);
1970   SDValue N1 = N->getOperand(1);
1971   SDValue CarryIn = N->getOperand(2);
1972
1973   // fold (sube x, y, false) -> (subc x, y)
1974   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1975     return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
1976
1977   return SDValue();
1978 }
1979
1980 SDValue DAGCombiner::visitMUL(SDNode *N) {
1981   SDValue N0 = N->getOperand(0);
1982   SDValue N1 = N->getOperand(1);
1983   EVT VT = N0.getValueType();
1984
1985   // fold (mul x, undef) -> 0
1986   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1987     return DAG.getConstant(0, SDLoc(N), VT);
1988
1989   bool N0IsConst = false;
1990   bool N1IsConst = false;
1991   APInt ConstValue0, ConstValue1;
1992   // fold vector ops
1993   if (VT.isVector()) {
1994     if (SDValue FoldedVOp = SimplifyVBinOp(N))
1995       return FoldedVOp;
1996
1997     N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1998     N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1999   } else {
2000     N0IsConst = isa<ConstantSDNode>(N0);
2001     if (N0IsConst)
2002       ConstValue0 = cast<ConstantSDNode>(N0)->getAPIntValue();
2003     N1IsConst = isa<ConstantSDNode>(N1);
2004     if (N1IsConst)
2005       ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue();
2006   }
2007
2008   // fold (mul c1, c2) -> c1*c2
2009   if (N0IsConst && N1IsConst)
2010     return DAG.FoldConstantArithmetic(ISD::MUL, SDLoc(N), VT,
2011                                       N0.getNode(), N1.getNode());
2012
2013   // canonicalize constant to RHS (vector doesn't have to splat)
2014   if (isConstantIntBuildVectorOrConstantInt(N0) &&
2015      !isConstantIntBuildVectorOrConstantInt(N1))
2016     return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
2017   // fold (mul x, 0) -> 0
2018   if (N1IsConst && ConstValue1 == 0)
2019     return N1;
2020   // We require a splat of the entire scalar bit width for non-contiguous
2021   // bit patterns.
2022   bool IsFullSplat =
2023     ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
2024   // fold (mul x, 1) -> x
2025   if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
2026     return N0;
2027   // fold (mul x, -1) -> 0-x
2028   if (N1IsConst && ConstValue1.isAllOnesValue()) {
2029     SDLoc DL(N);
2030     return DAG.getNode(ISD::SUB, DL, VT,
2031                        DAG.getConstant(0, DL, VT), N0);
2032   }
2033   // fold (mul x, (1 << c)) -> x << c
2034   if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat) {
2035     SDLoc DL(N);
2036     return DAG.getNode(ISD::SHL, DL, VT, N0,
2037                        DAG.getConstant(ConstValue1.logBase2(), DL,
2038                                        getShiftAmountTy(N0.getValueType())));
2039   }
2040   // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
2041   if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
2042     unsigned Log2Val = (-ConstValue1).logBase2();
2043     SDLoc DL(N);
2044     // FIXME: If the input is something that is easily negated (e.g. a
2045     // single-use add), we should put the negate there.
2046     return DAG.getNode(ISD::SUB, DL, VT,
2047                        DAG.getConstant(0, DL, VT),
2048                        DAG.getNode(ISD::SHL, DL, VT, N0,
2049                             DAG.getConstant(Log2Val, DL,
2050                                       getShiftAmountTy(N0.getValueType()))));
2051   }
2052
2053   APInt Val;
2054   // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
2055   if (N1IsConst && N0.getOpcode() == ISD::SHL &&
2056       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2057                      isa<ConstantSDNode>(N0.getOperand(1)))) {
2058     SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
2059                              N1, N0.getOperand(1));
2060     AddToWorklist(C3.getNode());
2061     return DAG.getNode(ISD::MUL, SDLoc(N), VT,
2062                        N0.getOperand(0), C3);
2063   }
2064
2065   // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2066   // use.
2067   {
2068     SDValue Sh(nullptr,0), Y(nullptr,0);
2069     // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
2070     if (N0.getOpcode() == ISD::SHL &&
2071         (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2072                        isa<ConstantSDNode>(N0.getOperand(1))) &&
2073         N0.getNode()->hasOneUse()) {
2074       Sh = N0; Y = N1;
2075     } else if (N1.getOpcode() == ISD::SHL &&
2076                isa<ConstantSDNode>(N1.getOperand(1)) &&
2077                N1.getNode()->hasOneUse()) {
2078       Sh = N1; Y = N0;
2079     }
2080
2081     if (Sh.getNode()) {
2082       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2083                                 Sh.getOperand(0), Y);
2084       return DAG.getNode(ISD::SHL, SDLoc(N), VT,
2085                          Mul, Sh.getOperand(1));
2086     }
2087   }
2088
2089   // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2090   if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
2091       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2092                      isa<ConstantSDNode>(N0.getOperand(1))))
2093     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2094                        DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2095                                    N0.getOperand(0), N1),
2096                        DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2097                                    N0.getOperand(1), N1));
2098
2099   // reassociate mul
2100   if (SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1))
2101     return RMUL;
2102
2103   return SDValue();
2104 }
2105
2106 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2107   SDValue N0 = N->getOperand(0);
2108   SDValue N1 = N->getOperand(1);
2109   EVT VT = N->getValueType(0);
2110
2111   // fold vector ops
2112   if (VT.isVector())
2113     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2114       return FoldedVOp;
2115
2116   // fold (sdiv c1, c2) -> c1/c2
2117   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2118   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2119   if (N0C && N1C && !N1C->isNullValue())
2120     return DAG.FoldConstantArithmetic(ISD::SDIV, SDLoc(N), VT, N0C, N1C);
2121   // fold (sdiv X, 1) -> X
2122   if (N1C && N1C->getAPIntValue() == 1LL)
2123     return N0;
2124   // fold (sdiv X, -1) -> 0-X
2125   if (N1C && N1C->isAllOnesValue()) {
2126     SDLoc DL(N);
2127     return DAG.getNode(ISD::SUB, DL, VT,
2128                        DAG.getConstant(0, DL, VT), N0);
2129   }
2130   // If we know the sign bits of both operands are zero, strength reduce to a
2131   // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
2132   if (!VT.isVector()) {
2133     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2134       return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
2135                          N0, N1);
2136   }
2137
2138   // fold (sdiv X, pow2) -> simple ops after legalize
2139   if (N1C && !N1C->isNullValue() && (N1C->getAPIntValue().isPowerOf2() ||
2140                                      (-N1C->getAPIntValue()).isPowerOf2())) {
2141     // If dividing by powers of two is cheap, then don't perform the following
2142     // fold.
2143     if (TLI.isPow2SDivCheap())
2144       return SDValue();
2145
2146     // Target-specific implementation of sdiv x, pow2.
2147     SDValue Res = BuildSDIVPow2(N);
2148     if (Res.getNode())
2149       return Res;
2150
2151     unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2152     SDLoc DL(N);
2153
2154     // Splat the sign bit into the register
2155     SDValue SGN =
2156         DAG.getNode(ISD::SRA, DL, VT, N0,
2157                     DAG.getConstant(VT.getScalarSizeInBits() - 1, DL,
2158                                     getShiftAmountTy(N0.getValueType())));
2159     AddToWorklist(SGN.getNode());
2160
2161     // Add (N0 < 0) ? abs2 - 1 : 0;
2162     SDValue SRL =
2163         DAG.getNode(ISD::SRL, DL, VT, SGN,
2164                     DAG.getConstant(VT.getScalarSizeInBits() - lg2, DL,
2165                                     getShiftAmountTy(SGN.getValueType())));
2166     SDValue ADD = DAG.getNode(ISD::ADD, DL, VT, N0, SRL);
2167     AddToWorklist(SRL.getNode());
2168     AddToWorklist(ADD.getNode());    // Divide by pow2
2169     SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, ADD,
2170                   DAG.getConstant(lg2, DL,
2171                                   getShiftAmountTy(ADD.getValueType())));
2172
2173     // If we're dividing by a positive value, we're done.  Otherwise, we must
2174     // negate the result.
2175     if (N1C->getAPIntValue().isNonNegative())
2176       return SRA;
2177
2178     AddToWorklist(SRA.getNode());
2179     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
2180   }
2181
2182   // If integer divide is expensive and we satisfy the requirements, emit an
2183   // alternate sequence.
2184   if (N1C && !TLI.isIntDivCheap()) {
2185     SDValue Op = BuildSDIV(N);
2186     if (Op.getNode()) return Op;
2187   }
2188
2189   // undef / X -> 0
2190   if (N0.getOpcode() == ISD::UNDEF)
2191     return DAG.getConstant(0, SDLoc(N), VT);
2192   // X / undef -> undef
2193   if (N1.getOpcode() == ISD::UNDEF)
2194     return N1;
2195
2196   return SDValue();
2197 }
2198
2199 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2200   SDValue N0 = N->getOperand(0);
2201   SDValue N1 = N->getOperand(1);
2202   EVT VT = N->getValueType(0);
2203
2204   // fold vector ops
2205   if (VT.isVector())
2206     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2207       return FoldedVOp;
2208
2209   // fold (udiv c1, c2) -> c1/c2
2210   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2211   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2212   if (N0C && N1C && !N1C->isNullValue())
2213     return DAG.FoldConstantArithmetic(ISD::UDIV, SDLoc(N), VT, N0C, N1C);
2214   // fold (udiv x, (1 << c)) -> x >>u c
2215   if (N1C && N1C->getAPIntValue().isPowerOf2()) {
2216     SDLoc DL(N);
2217     return DAG.getNode(ISD::SRL, DL, VT, N0,
2218                        DAG.getConstant(N1C->getAPIntValue().logBase2(), DL,
2219                                        getShiftAmountTy(N0.getValueType())));
2220   }
2221   // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2222   if (N1.getOpcode() == ISD::SHL) {
2223     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2224       if (SHC->getAPIntValue().isPowerOf2()) {
2225         EVT ADDVT = N1.getOperand(1).getValueType();
2226         SDLoc DL(N);
2227         SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT,
2228                                   N1.getOperand(1),
2229                                   DAG.getConstant(SHC->getAPIntValue()
2230                                                                   .logBase2(),
2231                                                   DL, ADDVT));
2232         AddToWorklist(Add.getNode());
2233         return DAG.getNode(ISD::SRL, DL, VT, N0, Add);
2234       }
2235     }
2236   }
2237   // fold (udiv x, c) -> alternate
2238   if (N1C && !TLI.isIntDivCheap()) {
2239     SDValue Op = BuildUDIV(N);
2240     if (Op.getNode()) return Op;
2241   }
2242
2243   // undef / X -> 0
2244   if (N0.getOpcode() == ISD::UNDEF)
2245     return DAG.getConstant(0, SDLoc(N), VT);
2246   // X / undef -> undef
2247   if (N1.getOpcode() == ISD::UNDEF)
2248     return N1;
2249
2250   return SDValue();
2251 }
2252
2253 SDValue DAGCombiner::visitSREM(SDNode *N) {
2254   SDValue N0 = N->getOperand(0);
2255   SDValue N1 = N->getOperand(1);
2256   EVT VT = N->getValueType(0);
2257
2258   // fold (srem c1, c2) -> c1%c2
2259   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2260   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2261   if (N0C && N1C && !N1C->isNullValue())
2262     return DAG.FoldConstantArithmetic(ISD::SREM, SDLoc(N), VT, N0C, N1C);
2263   // If we know the sign bits of both operands are zero, strength reduce to a
2264   // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2265   if (!VT.isVector()) {
2266     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2267       return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2268   }
2269
2270   // If X/C can be simplified by the division-by-constant logic, lower
2271   // X%C to the equivalent of X-X/C*C.
2272   if (N1C && !N1C->isNullValue()) {
2273     SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2274     AddToWorklist(Div.getNode());
2275     SDValue OptimizedDiv = combine(Div.getNode());
2276     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2277       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2278                                 OptimizedDiv, N1);
2279       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2280       AddToWorklist(Mul.getNode());
2281       return Sub;
2282     }
2283   }
2284
2285   // undef % X -> 0
2286   if (N0.getOpcode() == ISD::UNDEF)
2287     return DAG.getConstant(0, SDLoc(N), VT);
2288   // X % undef -> undef
2289   if (N1.getOpcode() == ISD::UNDEF)
2290     return N1;
2291
2292   return SDValue();
2293 }
2294
2295 SDValue DAGCombiner::visitUREM(SDNode *N) {
2296   SDValue N0 = N->getOperand(0);
2297   SDValue N1 = N->getOperand(1);
2298   EVT VT = N->getValueType(0);
2299
2300   // fold (urem c1, c2) -> c1%c2
2301   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2302   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2303   if (N0C && N1C && !N1C->isNullValue())
2304     return DAG.FoldConstantArithmetic(ISD::UREM, SDLoc(N), VT, N0C, N1C);
2305   // fold (urem x, pow2) -> (and x, pow2-1)
2306   if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2()) {
2307     SDLoc DL(N);
2308     return DAG.getNode(ISD::AND, DL, VT, N0,
2309                        DAG.getConstant(N1C->getAPIntValue() - 1, DL, VT));
2310   }
2311   // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2312   if (N1.getOpcode() == ISD::SHL) {
2313     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2314       if (SHC->getAPIntValue().isPowerOf2()) {
2315         SDLoc DL(N);
2316         SDValue Add =
2317           DAG.getNode(ISD::ADD, DL, VT, N1,
2318                  DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL,
2319                                  VT));
2320         AddToWorklist(Add.getNode());
2321         return DAG.getNode(ISD::AND, DL, VT, N0, Add);
2322       }
2323     }
2324   }
2325
2326   // If X/C can be simplified by the division-by-constant logic, lower
2327   // X%C to the equivalent of X-X/C*C.
2328   if (N1C && !N1C->isNullValue()) {
2329     SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2330     AddToWorklist(Div.getNode());
2331     SDValue OptimizedDiv = combine(Div.getNode());
2332     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2333       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2334                                 OptimizedDiv, N1);
2335       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2336       AddToWorklist(Mul.getNode());
2337       return Sub;
2338     }
2339   }
2340
2341   // undef % X -> 0
2342   if (N0.getOpcode() == ISD::UNDEF)
2343     return DAG.getConstant(0, SDLoc(N), VT);
2344   // X % undef -> undef
2345   if (N1.getOpcode() == ISD::UNDEF)
2346     return N1;
2347
2348   return SDValue();
2349 }
2350
2351 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2352   SDValue N0 = N->getOperand(0);
2353   SDValue N1 = N->getOperand(1);
2354   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2355   EVT VT = N->getValueType(0);
2356   SDLoc DL(N);
2357
2358   // fold (mulhs x, 0) -> 0
2359   if (isNullConstant(N1))
2360     return N1;
2361   // fold (mulhs x, 1) -> (sra x, size(x)-1)
2362   if (N1C && N1C->getAPIntValue() == 1) {
2363     SDLoc DL(N);
2364     return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0,
2365                        DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2366                                        DL,
2367                                        getShiftAmountTy(N0.getValueType())));
2368   }
2369   // fold (mulhs x, undef) -> 0
2370   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2371     return DAG.getConstant(0, SDLoc(N), VT);
2372
2373   // If the type twice as wide is legal, transform the mulhs to a wider multiply
2374   // plus a shift.
2375   if (VT.isSimple() && !VT.isVector()) {
2376     MVT Simple = VT.getSimpleVT();
2377     unsigned SimpleSize = Simple.getSizeInBits();
2378     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2379     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2380       N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2381       N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2382       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2383       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2384             DAG.getConstant(SimpleSize, DL,
2385                             getShiftAmountTy(N1.getValueType())));
2386       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2387     }
2388   }
2389
2390   return SDValue();
2391 }
2392
2393 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2394   SDValue N0 = N->getOperand(0);
2395   SDValue N1 = N->getOperand(1);
2396   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2397   EVT VT = N->getValueType(0);
2398   SDLoc DL(N);
2399
2400   // fold (mulhu x, 0) -> 0
2401   if (isNullConstant(N1))
2402     return N1;
2403   // fold (mulhu x, 1) -> 0
2404   if (N1C && N1C->getAPIntValue() == 1)
2405     return DAG.getConstant(0, DL, N0.getValueType());
2406   // fold (mulhu x, undef) -> 0
2407   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2408     return DAG.getConstant(0, DL, VT);
2409
2410   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2411   // plus a shift.
2412   if (VT.isSimple() && !VT.isVector()) {
2413     MVT Simple = VT.getSimpleVT();
2414     unsigned SimpleSize = Simple.getSizeInBits();
2415     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2416     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2417       N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2418       N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2419       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2420       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2421             DAG.getConstant(SimpleSize, DL,
2422                             getShiftAmountTy(N1.getValueType())));
2423       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2424     }
2425   }
2426
2427   return SDValue();
2428 }
2429
2430 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
2431 /// give the opcodes for the two computations that are being performed. Return
2432 /// true if a simplification was made.
2433 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2434                                                 unsigned HiOp) {
2435   // If the high half is not needed, just compute the low half.
2436   bool HiExists = N->hasAnyUseOfValue(1);
2437   if (!HiExists &&
2438       (!LegalOperations ||
2439        TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2440     SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2441     return CombineTo(N, Res, Res);
2442   }
2443
2444   // If the low half is not needed, just compute the high half.
2445   bool LoExists = N->hasAnyUseOfValue(0);
2446   if (!LoExists &&
2447       (!LegalOperations ||
2448        TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2449     SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2450     return CombineTo(N, Res, Res);
2451   }
2452
2453   // If both halves are used, return as it is.
2454   if (LoExists && HiExists)
2455     return SDValue();
2456
2457   // If the two computed results can be simplified separately, separate them.
2458   if (LoExists) {
2459     SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2460     AddToWorklist(Lo.getNode());
2461     SDValue LoOpt = combine(Lo.getNode());
2462     if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2463         (!LegalOperations ||
2464          TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2465       return CombineTo(N, LoOpt, LoOpt);
2466   }
2467
2468   if (HiExists) {
2469     SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2470     AddToWorklist(Hi.getNode());
2471     SDValue HiOpt = combine(Hi.getNode());
2472     if (HiOpt.getNode() && HiOpt != Hi &&
2473         (!LegalOperations ||
2474          TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2475       return CombineTo(N, HiOpt, HiOpt);
2476   }
2477
2478   return SDValue();
2479 }
2480
2481 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2482   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2483   if (Res.getNode()) return Res;
2484
2485   EVT VT = N->getValueType(0);
2486   SDLoc DL(N);
2487
2488   // If the type is twice as wide is legal, transform the mulhu to a wider
2489   // multiply plus a shift.
2490   if (VT.isSimple() && !VT.isVector()) {
2491     MVT Simple = VT.getSimpleVT();
2492     unsigned SimpleSize = Simple.getSizeInBits();
2493     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2494     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2495       SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2496       SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2497       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2498       // Compute the high part as N1.
2499       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2500             DAG.getConstant(SimpleSize, DL,
2501                             getShiftAmountTy(Lo.getValueType())));
2502       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2503       // Compute the low part as N0.
2504       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2505       return CombineTo(N, Lo, Hi);
2506     }
2507   }
2508
2509   return SDValue();
2510 }
2511
2512 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2513   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2514   if (Res.getNode()) return Res;
2515
2516   EVT VT = N->getValueType(0);
2517   SDLoc DL(N);
2518
2519   // If the type is twice as wide is legal, transform the mulhu to a wider
2520   // multiply plus a shift.
2521   if (VT.isSimple() && !VT.isVector()) {
2522     MVT Simple = VT.getSimpleVT();
2523     unsigned SimpleSize = Simple.getSizeInBits();
2524     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2525     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2526       SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2527       SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2528       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2529       // Compute the high part as N1.
2530       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2531             DAG.getConstant(SimpleSize, DL,
2532                             getShiftAmountTy(Lo.getValueType())));
2533       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2534       // Compute the low part as N0.
2535       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2536       return CombineTo(N, Lo, Hi);
2537     }
2538   }
2539
2540   return SDValue();
2541 }
2542
2543 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2544   // (smulo x, 2) -> (saddo x, x)
2545   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2546     if (C2->getAPIntValue() == 2)
2547       return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2548                          N->getOperand(0), N->getOperand(0));
2549
2550   return SDValue();
2551 }
2552
2553 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2554   // (umulo x, 2) -> (uaddo x, x)
2555   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2556     if (C2->getAPIntValue() == 2)
2557       return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2558                          N->getOperand(0), N->getOperand(0));
2559
2560   return SDValue();
2561 }
2562
2563 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2564   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2565   if (Res.getNode()) return Res;
2566
2567   return SDValue();
2568 }
2569
2570 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2571   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2572   if (Res.getNode()) return Res;
2573
2574   return SDValue();
2575 }
2576
2577 /// If this is a binary operator with two operands of the same opcode, try to
2578 /// simplify it.
2579 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2580   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2581   EVT VT = N0.getValueType();
2582   assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2583
2584   // Bail early if none of these transforms apply.
2585   if (N0.getNode()->getNumOperands() == 0) return SDValue();
2586
2587   // For each of OP in AND/OR/XOR:
2588   // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2589   // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2590   // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2591   // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y))
2592   // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2593   //
2594   // do not sink logical op inside of a vector extend, since it may combine
2595   // into a vsetcc.
2596   EVT Op0VT = N0.getOperand(0).getValueType();
2597   if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2598        N0.getOpcode() == ISD::SIGN_EXTEND ||
2599        N0.getOpcode() == ISD::BSWAP ||
2600        // Avoid infinite looping with PromoteIntBinOp.
2601        (N0.getOpcode() == ISD::ANY_EXTEND &&
2602         (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2603        (N0.getOpcode() == ISD::TRUNCATE &&
2604         (!TLI.isZExtFree(VT, Op0VT) ||
2605          !TLI.isTruncateFree(Op0VT, VT)) &&
2606         TLI.isTypeLegal(Op0VT))) &&
2607       !VT.isVector() &&
2608       Op0VT == N1.getOperand(0).getValueType() &&
2609       (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2610     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2611                                  N0.getOperand(0).getValueType(),
2612                                  N0.getOperand(0), N1.getOperand(0));
2613     AddToWorklist(ORNode.getNode());
2614     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2615   }
2616
2617   // For each of OP in SHL/SRL/SRA/AND...
2618   //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2619   //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
2620   //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2621   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2622        N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2623       N0.getOperand(1) == N1.getOperand(1)) {
2624     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2625                                  N0.getOperand(0).getValueType(),
2626                                  N0.getOperand(0), N1.getOperand(0));
2627     AddToWorklist(ORNode.getNode());
2628     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2629                        ORNode, N0.getOperand(1));
2630   }
2631
2632   // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2633   // Only perform this optimization after type legalization and before
2634   // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2635   // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2636   // we don't want to undo this promotion.
2637   // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2638   // on scalars.
2639   if ((N0.getOpcode() == ISD::BITCAST ||
2640        N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2641       Level == AfterLegalizeTypes) {
2642     SDValue In0 = N0.getOperand(0);
2643     SDValue In1 = N1.getOperand(0);
2644     EVT In0Ty = In0.getValueType();
2645     EVT In1Ty = In1.getValueType();
2646     SDLoc DL(N);
2647     // If both incoming values are integers, and the original types are the
2648     // same.
2649     if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2650       SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2651       SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2652       AddToWorklist(Op.getNode());
2653       return BC;
2654     }
2655   }
2656
2657   // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2658   // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2659   // If both shuffles use the same mask, and both shuffle within a single
2660   // vector, then it is worthwhile to move the swizzle after the operation.
2661   // The type-legalizer generates this pattern when loading illegal
2662   // vector types from memory. In many cases this allows additional shuffle
2663   // optimizations.
2664   // There are other cases where moving the shuffle after the xor/and/or
2665   // is profitable even if shuffles don't perform a swizzle.
2666   // If both shuffles use the same mask, and both shuffles have the same first
2667   // or second operand, then it might still be profitable to move the shuffle
2668   // after the xor/and/or operation.
2669   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2670     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2671     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2672
2673     assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2674            "Inputs to shuffles are not the same type");
2675
2676     // Check that both shuffles use the same mask. The masks are known to be of
2677     // the same length because the result vector type is the same.
2678     // Check also that shuffles have only one use to avoid introducing extra
2679     // instructions.
2680     if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2681         SVN0->getMask().equals(SVN1->getMask())) {
2682       SDValue ShOp = N0->getOperand(1);
2683
2684       // Don't try to fold this node if it requires introducing a
2685       // build vector of all zeros that might be illegal at this stage.
2686       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2687         if (!LegalTypes)
2688           ShOp = DAG.getConstant(0, SDLoc(N), VT);
2689         else
2690           ShOp = SDValue();
2691       }
2692
2693       // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2694       // (OR  (shuf (A, C), shuf (B, C)) -> shuf (OR  (A, B), C)
2695       // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2696       if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2697         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2698                                       N0->getOperand(0), N1->getOperand(0));
2699         AddToWorklist(NewNode.getNode());
2700         return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2701                                     &SVN0->getMask()[0]);
2702       }
2703
2704       // Don't try to fold this node if it requires introducing a
2705       // build vector of all zeros that might be illegal at this stage.
2706       ShOp = N0->getOperand(0);
2707       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2708         if (!LegalTypes)
2709           ShOp = DAG.getConstant(0, SDLoc(N), VT);
2710         else
2711           ShOp = SDValue();
2712       }
2713
2714       // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2715       // (OR  (shuf (C, A), shuf (C, B)) -> shuf (C, OR  (A, B))
2716       // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2717       if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2718         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2719                                       N0->getOperand(1), N1->getOperand(1));
2720         AddToWorklist(NewNode.getNode());
2721         return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2722                                     &SVN0->getMask()[0]);
2723       }
2724     }
2725   }
2726
2727   return SDValue();
2728 }
2729
2730 /// This contains all DAGCombine rules which reduce two values combined by
2731 /// an And operation to a single value. This makes them reusable in the context
2732 /// of visitSELECT(). Rules involving constants are not included as
2733 /// visitSELECT() already handles those cases.
2734 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1,
2735                                   SDNode *LocReference) {
2736   EVT VT = N1.getValueType();
2737
2738   // fold (and x, undef) -> 0
2739   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2740     return DAG.getConstant(0, SDLoc(LocReference), VT);
2741   // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2742   SDValue LL, LR, RL, RR, CC0, CC1;
2743   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2744     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2745     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2746
2747     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2748         LL.getValueType().isInteger()) {
2749       // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2750       if (isNullConstant(LR) && Op1 == ISD::SETEQ) {
2751         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2752                                      LR.getValueType(), LL, RL);
2753         AddToWorklist(ORNode.getNode());
2754         return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2755       }
2756       // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2757       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2758         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2759                                       LR.getValueType(), LL, RL);
2760         AddToWorklist(ANDNode.getNode());
2761         return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
2762       }
2763       // fold (and (setgt X,  -1), (setgt Y,  -1)) -> (setgt (or X, Y), -1)
2764       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2765         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2766                                      LR.getValueType(), LL, RL);
2767         AddToWorklist(ORNode.getNode());
2768         return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2769       }
2770     }
2771     // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2772     if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2773         Op0 == Op1 && LL.getValueType().isInteger() &&
2774       Op0 == ISD::SETNE && ((isNullConstant(LR) &&
2775                                  cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2776                                 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2777                                  isNullConstant(RR)))) {
2778       SDLoc DL(N0);
2779       SDValue ADDNode = DAG.getNode(ISD::ADD, DL, LL.getValueType(),
2780                                     LL, DAG.getConstant(1, DL,
2781                                                         LL.getValueType()));
2782       AddToWorklist(ADDNode.getNode());
2783       return DAG.getSetCC(SDLoc(LocReference), VT, ADDNode,
2784                           DAG.getConstant(2, DL, LL.getValueType()),
2785                           ISD::SETUGE);
2786     }
2787     // canonicalize equivalent to ll == rl
2788     if (LL == RR && LR == RL) {
2789       Op1 = ISD::getSetCCSwappedOperands(Op1);
2790       std::swap(RL, RR);
2791     }
2792     if (LL == RL && LR == RR) {
2793       bool isInteger = LL.getValueType().isInteger();
2794       ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2795       if (Result != ISD::SETCC_INVALID &&
2796           (!LegalOperations ||
2797            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2798             TLI.isOperationLegal(ISD::SETCC,
2799                             getSetCCResultType(N0.getSimpleValueType())))))
2800         return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
2801                             LL, LR, Result);
2802     }
2803   }
2804
2805   if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2806       VT.getSizeInBits() <= 64) {
2807     if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2808       APInt ADDC = ADDI->getAPIntValue();
2809       if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2810         // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2811         // immediate for an add, but it is legal if its top c2 bits are set,
2812         // transform the ADD so the immediate doesn't need to be materialized
2813         // in a register.
2814         if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2815           APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2816                                              SRLI->getZExtValue());
2817           if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2818             ADDC |= Mask;
2819             if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2820               SDLoc DL(N0);
2821               SDValue NewAdd =
2822                 DAG.getNode(ISD::ADD, DL, VT,
2823                             N0.getOperand(0), DAG.getConstant(ADDC, DL, VT));
2824               CombineTo(N0.getNode(), NewAdd);
2825               // Return N so it doesn't get rechecked!
2826               return SDValue(LocReference, 0);
2827             }
2828           }
2829         }
2830       }
2831     }
2832   }
2833
2834   return SDValue();
2835 }
2836
2837 SDValue DAGCombiner::visitAND(SDNode *N) {
2838   SDValue N0 = N->getOperand(0);
2839   SDValue N1 = N->getOperand(1);
2840   EVT VT = N1.getValueType();
2841
2842   // fold vector ops
2843   if (VT.isVector()) {
2844     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2845       return FoldedVOp;
2846
2847     // fold (and x, 0) -> 0, vector edition
2848     if (ISD::isBuildVectorAllZeros(N0.getNode()))
2849       // do not return N0, because undef node may exist in N0
2850       return DAG.getConstant(
2851           APInt::getNullValue(
2852               N0.getValueType().getScalarType().getSizeInBits()),
2853           SDLoc(N), N0.getValueType());
2854     if (ISD::isBuildVectorAllZeros(N1.getNode()))
2855       // do not return N1, because undef node may exist in N1
2856       return DAG.getConstant(
2857           APInt::getNullValue(
2858               N1.getValueType().getScalarType().getSizeInBits()),
2859           SDLoc(N), N1.getValueType());
2860
2861     // fold (and x, -1) -> x, vector edition
2862     if (ISD::isBuildVectorAllOnes(N0.getNode()))
2863       return N1;
2864     if (ISD::isBuildVectorAllOnes(N1.getNode()))
2865       return N0;
2866   }
2867
2868   // fold (and c1, c2) -> c1&c2
2869   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2870   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2871   if (N0C && N1C)
2872     return DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, N0C, N1C);
2873   // canonicalize constant to RHS
2874   if (isConstantIntBuildVectorOrConstantInt(N0) &&
2875      !isConstantIntBuildVectorOrConstantInt(N1))
2876     return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2877   // fold (and x, -1) -> x
2878   if (N1C && N1C->isAllOnesValue())
2879     return N0;
2880   // if (and x, c) is known to be zero, return 0
2881   unsigned BitWidth = VT.getScalarType().getSizeInBits();
2882   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2883                                    APInt::getAllOnesValue(BitWidth)))
2884     return DAG.getConstant(0, SDLoc(N), VT);
2885   // reassociate and
2886   if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1))
2887     return RAND;
2888   // fold (and (or x, C), D) -> D if (C & D) == D
2889   if (N1C && N0.getOpcode() == ISD::OR)
2890     if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2891       if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2892         return N1;
2893   // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2894   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2895     SDValue N0Op0 = N0.getOperand(0);
2896     APInt Mask = ~N1C->getAPIntValue();
2897     Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2898     if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2899       SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2900                                  N0.getValueType(), N0Op0);
2901
2902       // Replace uses of the AND with uses of the Zero extend node.
2903       CombineTo(N, Zext);
2904
2905       // We actually want to replace all uses of the any_extend with the
2906       // zero_extend, to avoid duplicating things.  This will later cause this
2907       // AND to be folded.
2908       CombineTo(N0.getNode(), Zext);
2909       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2910     }
2911   }
2912   // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2913   // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2914   // already be zero by virtue of the width of the base type of the load.
2915   //
2916   // the 'X' node here can either be nothing or an extract_vector_elt to catch
2917   // more cases.
2918   if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2919        N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2920       N0.getOpcode() == ISD::LOAD) {
2921     LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2922                                          N0 : N0.getOperand(0) );
2923
2924     // Get the constant (if applicable) the zero'th operand is being ANDed with.
2925     // This can be a pure constant or a vector splat, in which case we treat the
2926     // vector as a scalar and use the splat value.
2927     APInt Constant = APInt::getNullValue(1);
2928     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2929       Constant = C->getAPIntValue();
2930     } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2931       APInt SplatValue, SplatUndef;
2932       unsigned SplatBitSize;
2933       bool HasAnyUndefs;
2934       bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2935                                              SplatBitSize, HasAnyUndefs);
2936       if (IsSplat) {
2937         // Undef bits can contribute to a possible optimisation if set, so
2938         // set them.
2939         SplatValue |= SplatUndef;
2940
2941         // The splat value may be something like "0x00FFFFFF", which means 0 for
2942         // the first vector value and FF for the rest, repeating. We need a mask
2943         // that will apply equally to all members of the vector, so AND all the
2944         // lanes of the constant together.
2945         EVT VT = Vector->getValueType(0);
2946         unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2947
2948         // If the splat value has been compressed to a bitlength lower
2949         // than the size of the vector lane, we need to re-expand it to
2950         // the lane size.
2951         if (BitWidth > SplatBitSize)
2952           for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2953                SplatBitSize < BitWidth;
2954                SplatBitSize = SplatBitSize * 2)
2955             SplatValue |= SplatValue.shl(SplatBitSize);
2956
2957         // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a
2958         // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value.
2959         if (SplatBitSize % BitWidth == 0) {
2960           Constant = APInt::getAllOnesValue(BitWidth);
2961           for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2962             Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2963         }
2964       }
2965     }
2966
2967     // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2968     // actually legal and isn't going to get expanded, else this is a false
2969     // optimisation.
2970     bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2971                                                     Load->getValueType(0),
2972                                                     Load->getMemoryVT());
2973
2974     // Resize the constant to the same size as the original memory access before
2975     // extension. If it is still the AllOnesValue then this AND is completely
2976     // unneeded.
2977     Constant =
2978       Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2979
2980     bool B;
2981     switch (Load->getExtensionType()) {
2982     default: B = false; break;
2983     case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2984     case ISD::ZEXTLOAD:
2985     case ISD::NON_EXTLOAD: B = true; break;
2986     }
2987
2988     if (B && Constant.isAllOnesValue()) {
2989       // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2990       // preserve semantics once we get rid of the AND.
2991       SDValue NewLoad(Load, 0);
2992       if (Load->getExtensionType() == ISD::EXTLOAD) {
2993         NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
2994                               Load->getValueType(0), SDLoc(Load),
2995                               Load->getChain(), Load->getBasePtr(),
2996                               Load->getOffset(), Load->getMemoryVT(),
2997                               Load->getMemOperand());
2998         // Replace uses of the EXTLOAD with the new ZEXTLOAD.
2999         if (Load->getNumValues() == 3) {
3000           // PRE/POST_INC loads have 3 values.
3001           SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
3002                            NewLoad.getValue(2) };
3003           CombineTo(Load, To, 3, true);
3004         } else {
3005           CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
3006         }
3007       }
3008
3009       // Fold the AND away, taking care not to fold to the old load node if we
3010       // replaced it.
3011       CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
3012
3013       return SDValue(N, 0); // Return N so it doesn't get rechecked!
3014     }
3015   }
3016
3017   // fold (and (load x), 255) -> (zextload x, i8)
3018   // fold (and (extload x, i16), 255) -> (zextload x, i8)
3019   // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
3020   if (N1C && (N0.getOpcode() == ISD::LOAD ||
3021               (N0.getOpcode() == ISD::ANY_EXTEND &&
3022                N0.getOperand(0).getOpcode() == ISD::LOAD))) {
3023     bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
3024     LoadSDNode *LN0 = HasAnyExt
3025       ? cast<LoadSDNode>(N0.getOperand(0))
3026       : cast<LoadSDNode>(N0);
3027     if (LN0->getExtensionType() != ISD::SEXTLOAD &&
3028         LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
3029       uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
3030       if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
3031         EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
3032         EVT LoadedVT = LN0->getMemoryVT();
3033         EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
3034
3035         if (ExtVT == LoadedVT &&
3036             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3037                                                     ExtVT))) {
3038
3039           SDValue NewLoad =
3040             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3041                            LN0->getChain(), LN0->getBasePtr(), ExtVT,
3042                            LN0->getMemOperand());
3043           AddToWorklist(N);
3044           CombineTo(LN0, NewLoad, NewLoad.getValue(1));
3045           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3046         }
3047
3048         // Do not change the width of a volatile load.
3049         // Do not generate loads of non-round integer types since these can
3050         // be expensive (and would be wrong if the type is not byte sized).
3051         if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
3052             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3053                                                     ExtVT))) {
3054           EVT PtrType = LN0->getOperand(1).getValueType();
3055
3056           unsigned Alignment = LN0->getAlignment();
3057           SDValue NewPtr = LN0->getBasePtr();
3058
3059           // For big endian targets, we need to add an offset to the pointer
3060           // to load the correct bytes.  For little endian systems, we merely
3061           // need to read fewer bytes from the same pointer.
3062           if (TLI.isBigEndian()) {
3063             unsigned LVTStoreBytes = LoadedVT.getStoreSize();
3064             unsigned EVTStoreBytes = ExtVT.getStoreSize();
3065             unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
3066             SDLoc DL(LN0);
3067             NewPtr = DAG.getNode(ISD::ADD, DL, PtrType,
3068                                  NewPtr, DAG.getConstant(PtrOff, DL, PtrType));
3069             Alignment = MinAlign(Alignment, PtrOff);
3070           }
3071
3072           AddToWorklist(NewPtr.getNode());
3073
3074           SDValue Load =
3075             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3076                            LN0->getChain(), NewPtr,
3077                            LN0->getPointerInfo(),
3078                            ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
3079                            LN0->isInvariant(), Alignment, LN0->getAAInfo());
3080           AddToWorklist(N);
3081           CombineTo(LN0, Load, Load.getValue(1));
3082           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3083         }
3084       }
3085     }
3086   }
3087
3088   if (SDValue Combined = visitANDLike(N0, N1, N))
3089     return Combined;
3090
3091   // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
3092   if (N0.getOpcode() == N1.getOpcode()) {
3093     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3094     if (Tmp.getNode()) return Tmp;
3095   }
3096
3097   // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
3098   // fold (and (sra)) -> (and (srl)) when possible.
3099   if (!VT.isVector() &&
3100       SimplifyDemandedBits(SDValue(N, 0)))
3101     return SDValue(N, 0);
3102
3103   // fold (zext_inreg (extload x)) -> (zextload x)
3104   if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
3105     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3106     EVT MemVT = LN0->getMemoryVT();
3107     // If we zero all the possible extended bits, then we can turn this into
3108     // a zextload if we are running before legalize or the operation is legal.
3109     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3110     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3111                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3112         ((!LegalOperations && !LN0->isVolatile()) ||
3113          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3114       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3115                                        LN0->getChain(), LN0->getBasePtr(),
3116                                        MemVT, LN0->getMemOperand());
3117       AddToWorklist(N);
3118       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3119       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3120     }
3121   }
3122   // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
3123   if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
3124       N0.hasOneUse()) {
3125     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3126     EVT MemVT = LN0->getMemoryVT();
3127     // If we zero all the possible extended bits, then we can turn this into
3128     // a zextload if we are running before legalize or the operation is legal.
3129     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3130     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3131                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3132         ((!LegalOperations && !LN0->isVolatile()) ||
3133          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3134       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3135                                        LN0->getChain(), LN0->getBasePtr(),
3136                                        MemVT, LN0->getMemOperand());
3137       AddToWorklist(N);
3138       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3139       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3140     }
3141   }
3142   // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3143   if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3144     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3145                                        N0.getOperand(1), false);
3146     if (BSwap.getNode())
3147       return BSwap;
3148   }
3149
3150   return SDValue();
3151 }
3152
3153 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
3154 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3155                                         bool DemandHighBits) {
3156   if (!LegalOperations)
3157     return SDValue();
3158
3159   EVT VT = N->getValueType(0);
3160   if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3161     return SDValue();
3162   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3163     return SDValue();
3164
3165   // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3166   bool LookPassAnd0 = false;
3167   bool LookPassAnd1 = false;
3168   if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3169       std::swap(N0, N1);
3170   if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3171       std::swap(N0, N1);
3172   if (N0.getOpcode() == ISD::AND) {
3173     if (!N0.getNode()->hasOneUse())
3174       return SDValue();
3175     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3176     if (!N01C || N01C->getZExtValue() != 0xFF00)
3177       return SDValue();
3178     N0 = N0.getOperand(0);
3179     LookPassAnd0 = true;
3180   }
3181
3182   if (N1.getOpcode() == ISD::AND) {
3183     if (!N1.getNode()->hasOneUse())
3184       return SDValue();
3185     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3186     if (!N11C || N11C->getZExtValue() != 0xFF)
3187       return SDValue();
3188     N1 = N1.getOperand(0);
3189     LookPassAnd1 = true;
3190   }
3191
3192   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3193     std::swap(N0, N1);
3194   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3195     return SDValue();
3196   if (!N0.getNode()->hasOneUse() ||
3197       !N1.getNode()->hasOneUse())
3198     return SDValue();
3199
3200   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3201   ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3202   if (!N01C || !N11C)
3203     return SDValue();
3204   if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3205     return SDValue();
3206
3207   // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3208   SDValue N00 = N0->getOperand(0);
3209   if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3210     if (!N00.getNode()->hasOneUse())
3211       return SDValue();
3212     ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3213     if (!N001C || N001C->getZExtValue() != 0xFF)
3214       return SDValue();
3215     N00 = N00.getOperand(0);
3216     LookPassAnd0 = true;
3217   }
3218
3219   SDValue N10 = N1->getOperand(0);
3220   if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3221     if (!N10.getNode()->hasOneUse())
3222       return SDValue();
3223     ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3224     if (!N101C || N101C->getZExtValue() != 0xFF00)
3225       return SDValue();
3226     N10 = N10.getOperand(0);
3227     LookPassAnd1 = true;
3228   }
3229
3230   if (N00 != N10)
3231     return SDValue();
3232
3233   // Make sure everything beyond the low halfword gets set to zero since the SRL
3234   // 16 will clear the top bits.
3235   unsigned OpSizeInBits = VT.getSizeInBits();
3236   if (DemandHighBits && OpSizeInBits > 16) {
3237     // If the left-shift isn't masked out then the only way this is a bswap is
3238     // if all bits beyond the low 8 are 0. In that case the entire pattern
3239     // reduces to a left shift anyway: leave it for other parts of the combiner.
3240     if (!LookPassAnd0)
3241       return SDValue();
3242
3243     // However, if the right shift isn't masked out then it might be because
3244     // it's not needed. See if we can spot that too.
3245     if (!LookPassAnd1 &&
3246         !DAG.MaskedValueIsZero(
3247             N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3248       return SDValue();
3249   }
3250
3251   SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3252   if (OpSizeInBits > 16) {
3253     SDLoc DL(N);
3254     Res = DAG.getNode(ISD::SRL, DL, VT, Res,
3255                       DAG.getConstant(OpSizeInBits - 16, DL,
3256                                       getShiftAmountTy(VT)));
3257   }
3258   return Res;
3259 }
3260
3261 /// Return true if the specified node is an element that makes up a 32-bit
3262 /// packed halfword byteswap.
3263 /// ((x & 0x000000ff) << 8) |
3264 /// ((x & 0x0000ff00) >> 8) |
3265 /// ((x & 0x00ff0000) << 8) |
3266 /// ((x & 0xff000000) >> 8)
3267 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
3268   if (!N.getNode()->hasOneUse())
3269     return false;
3270
3271   unsigned Opc = N.getOpcode();
3272   if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3273     return false;
3274
3275   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3276   if (!N1C)
3277     return false;
3278
3279   unsigned Num;
3280   switch (N1C->getZExtValue()) {
3281   default:
3282     return false;
3283   case 0xFF:       Num = 0; break;
3284   case 0xFF00:     Num = 1; break;
3285   case 0xFF0000:   Num = 2; break;
3286   case 0xFF000000: Num = 3; break;
3287   }
3288
3289   // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3290   SDValue N0 = N.getOperand(0);
3291   if (Opc == ISD::AND) {
3292     if (Num == 0 || Num == 2) {
3293       // (x >> 8) & 0xff
3294       // (x >> 8) & 0xff0000
3295       if (N0.getOpcode() != ISD::SRL)
3296         return false;
3297       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3298       if (!C || C->getZExtValue() != 8)
3299         return false;
3300     } else {
3301       // (x << 8) & 0xff00
3302       // (x << 8) & 0xff000000
3303       if (N0.getOpcode() != ISD::SHL)
3304         return false;
3305       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3306       if (!C || C->getZExtValue() != 8)
3307         return false;
3308     }
3309   } else if (Opc == ISD::SHL) {
3310     // (x & 0xff) << 8
3311     // (x & 0xff0000) << 8
3312     if (Num != 0 && Num != 2)
3313       return false;
3314     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3315     if (!C || C->getZExtValue() != 8)
3316       return false;
3317   } else { // Opc == ISD::SRL
3318     // (x & 0xff00) >> 8
3319     // (x & 0xff000000) >> 8
3320     if (Num != 1 && Num != 3)
3321       return false;
3322     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3323     if (!C || C->getZExtValue() != 8)
3324       return false;
3325   }
3326
3327   if (Parts[Num])
3328     return false;
3329
3330   Parts[Num] = N0.getOperand(0).getNode();
3331   return true;
3332 }
3333
3334 /// Match a 32-bit packed halfword bswap. That is
3335 /// ((x & 0x000000ff) << 8) |
3336 /// ((x & 0x0000ff00) >> 8) |
3337 /// ((x & 0x00ff0000) << 8) |
3338 /// ((x & 0xff000000) >> 8)
3339 /// => (rotl (bswap x), 16)
3340 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3341   if (!LegalOperations)
3342     return SDValue();
3343
3344   EVT VT = N->getValueType(0);
3345   if (VT != MVT::i32)
3346     return SDValue();
3347   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3348     return SDValue();
3349
3350   // Look for either
3351   // (or (or (and), (and)), (or (and), (and)))
3352   // (or (or (or (and), (and)), (and)), (and))
3353   if (N0.getOpcode() != ISD::OR)
3354     return SDValue();
3355   SDValue N00 = N0.getOperand(0);
3356   SDValue N01 = N0.getOperand(1);
3357   SDNode *Parts[4] = {};
3358
3359   if (N1.getOpcode() == ISD::OR &&
3360       N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3361     // (or (or (and), (and)), (or (and), (and)))
3362     SDValue N000 = N00.getOperand(0);
3363     if (!isBSwapHWordElement(N000, Parts))
3364       return SDValue();
3365
3366     SDValue N001 = N00.getOperand(1);
3367     if (!isBSwapHWordElement(N001, Parts))
3368       return SDValue();
3369     SDValue N010 = N01.getOperand(0);
3370     if (!isBSwapHWordElement(N010, Parts))
3371       return SDValue();
3372     SDValue N011 = N01.getOperand(1);
3373     if (!isBSwapHWordElement(N011, Parts))
3374       return SDValue();
3375   } else {
3376     // (or (or (or (and), (and)), (and)), (and))
3377     if (!isBSwapHWordElement(N1, Parts))
3378       return SDValue();
3379     if (!isBSwapHWordElement(N01, Parts))
3380       return SDValue();
3381     if (N00.getOpcode() != ISD::OR)
3382       return SDValue();
3383     SDValue N000 = N00.getOperand(0);
3384     if (!isBSwapHWordElement(N000, Parts))
3385       return SDValue();
3386     SDValue N001 = N00.getOperand(1);
3387     if (!isBSwapHWordElement(N001, Parts))
3388       return SDValue();
3389   }
3390
3391   // Make sure the parts are all coming from the same node.
3392   if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3393     return SDValue();
3394
3395   SDLoc DL(N);
3396   SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT,
3397                               SDValue(Parts[0], 0));
3398
3399   // Result of the bswap should be rotated by 16. If it's not legal, then
3400   // do  (x << 16) | (x >> 16).
3401   SDValue ShAmt = DAG.getConstant(16, DL, getShiftAmountTy(VT));
3402   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3403     return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt);
3404   if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3405     return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt);
3406   return DAG.getNode(ISD::OR, DL, VT,
3407                      DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt),
3408                      DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt));
3409 }
3410
3411 /// This contains all DAGCombine rules which reduce two values combined by
3412 /// an Or operation to a single value \see visitANDLike().
3413 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *LocReference) {
3414   EVT VT = N1.getValueType();
3415   // fold (or x, undef) -> -1
3416   if (!LegalOperations &&
3417       (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3418     EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3419     return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()),
3420                            SDLoc(LocReference), VT);
3421   }
3422   // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3423   SDValue LL, LR, RL, RR, CC0, CC1;
3424   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3425     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3426     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3427
3428     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3429         LL.getValueType().isInteger()) {
3430       // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3431       // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3432       if (isNullConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3433         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3434                                      LR.getValueType(), LL, RL);
3435         AddToWorklist(ORNode.getNode());
3436         return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
3437       }
3438       // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3439       // fold (or (setgt X, -1), (setgt Y  -1)) -> (setgt (and X, Y), -1)
3440       if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3441           (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3442         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3443                                       LR.getValueType(), LL, RL);
3444         AddToWorklist(ANDNode.getNode());
3445         return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
3446       }
3447     }
3448     // canonicalize equivalent to ll == rl
3449     if (LL == RR && LR == RL) {
3450       Op1 = ISD::getSetCCSwappedOperands(Op1);
3451       std::swap(RL, RR);
3452     }
3453     if (LL == RL && LR == RR) {
3454       bool isInteger = LL.getValueType().isInteger();
3455       ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3456       if (Result != ISD::SETCC_INVALID &&
3457           (!LegalOperations ||
3458            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3459             TLI.isOperationLegal(ISD::SETCC,
3460               getSetCCResultType(N0.getValueType())))))
3461         return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
3462                             LL, LR, Result);
3463     }
3464   }
3465
3466   // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
3467   if (N0.getOpcode() == ISD::AND &&
3468       N1.getOpcode() == ISD::AND &&
3469       N0.getOperand(1).getOpcode() == ISD::Constant &&
3470       N1.getOperand(1).getOpcode() == ISD::Constant &&
3471       // Don't increase # computations.
3472       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3473     // We can only do this xform if we know that bits from X that are set in C2
3474     // but not in C1 are already zero.  Likewise for Y.
3475     const APInt &LHSMask =
3476       cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3477     const APInt &RHSMask =
3478       cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3479
3480     if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3481         DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3482       SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3483                               N0.getOperand(0), N1.getOperand(0));
3484       SDLoc DL(LocReference);
3485       return DAG.getNode(ISD::AND, DL, VT, X,
3486                          DAG.getConstant(LHSMask | RHSMask, DL, VT));
3487     }
3488   }
3489
3490   // (or (and X, M), (and X, N)) -> (and X, (or M, N))
3491   if (N0.getOpcode() == ISD::AND &&
3492       N1.getOpcode() == ISD::AND &&
3493       N0.getOperand(0) == N1.getOperand(0) &&
3494       // Don't increase # computations.
3495       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3496     SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3497                             N0.getOperand(1), N1.getOperand(1));
3498     return DAG.getNode(ISD::AND, SDLoc(LocReference), VT, N0.getOperand(0), X);
3499   }
3500
3501   return SDValue();
3502 }
3503
3504 SDValue DAGCombiner::visitOR(SDNode *N) {
3505   SDValue N0 = N->getOperand(0);
3506   SDValue N1 = N->getOperand(1);
3507   EVT VT = N1.getValueType();
3508
3509   // fold vector ops
3510   if (VT.isVector()) {
3511     if (SDValue FoldedVOp = SimplifyVBinOp(N))
3512       return FoldedVOp;
3513
3514     // fold (or x, 0) -> x, vector edition
3515     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3516       return N1;
3517     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3518       return N0;
3519
3520     // fold (or x, -1) -> -1, vector edition
3521     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3522       // do not return N0, because undef node may exist in N0
3523       return DAG.getConstant(
3524           APInt::getAllOnesValue(
3525               N0.getValueType().getScalarType().getSizeInBits()),
3526           SDLoc(N), N0.getValueType());
3527     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3528       // do not return N1, because undef node may exist in N1
3529       return DAG.getConstant(
3530           APInt::getAllOnesValue(
3531               N1.getValueType().getScalarType().getSizeInBits()),
3532           SDLoc(N), N1.getValueType());
3533
3534     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3535     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3536     // Do this only if the resulting shuffle is legal.
3537     if (isa<ShuffleVectorSDNode>(N0) &&
3538         isa<ShuffleVectorSDNode>(N1) &&
3539         // Avoid folding a node with illegal type.
3540         TLI.isTypeLegal(VT) &&
3541         N0->getOperand(1) == N1->getOperand(1) &&
3542         ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3543       bool CanFold = true;
3544       unsigned NumElts = VT.getVectorNumElements();
3545       const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3546       const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3547       // We construct two shuffle masks:
3548       // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3549       // and N1 as the second operand.
3550       // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3551       // and N0 as the second operand.
3552       // We do this because OR is commutable and therefore there might be
3553       // two ways to fold this node into a shuffle.
3554       SmallVector<int,4> Mask1;
3555       SmallVector<int,4> Mask2;
3556
3557       for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3558         int M0 = SV0->getMaskElt(i);
3559         int M1 = SV1->getMaskElt(i);
3560
3561         // Both shuffle indexes are undef. Propagate Undef.
3562         if (M0 < 0 && M1 < 0) {
3563           Mask1.push_back(M0);
3564           Mask2.push_back(M0);
3565           continue;
3566         }
3567
3568         if (M0 < 0 || M1 < 0 ||
3569             (M0 < (int)NumElts && M1 < (int)NumElts) ||
3570             (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3571           CanFold = false;
3572           break;
3573         }
3574
3575         Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3576         Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3577       }
3578
3579       if (CanFold) {
3580         // Fold this sequence only if the resulting shuffle is 'legal'.
3581         if (TLI.isShuffleMaskLegal(Mask1, VT))
3582           return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3583                                       N1->getOperand(0), &Mask1[0]);
3584         if (TLI.isShuffleMaskLegal(Mask2, VT))
3585           return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3586                                       N0->getOperand(0), &Mask2[0]);
3587       }
3588     }
3589   }
3590
3591   // fold (or c1, c2) -> c1|c2
3592   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3593   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3594   if (N0C && N1C)
3595     return DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N), VT, N0C, N1C);
3596   // canonicalize constant to RHS
3597   if (isConstantIntBuildVectorOrConstantInt(N0) &&
3598      !isConstantIntBuildVectorOrConstantInt(N1))
3599     return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3600   // fold (or x, 0) -> x
3601   if (isNullConstant(N1))
3602     return N0;
3603   // fold (or x, -1) -> -1
3604   if (N1C && N1C->isAllOnesValue())
3605     return N1;
3606   // fold (or x, c) -> c iff (x & ~c) == 0
3607   if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3608     return N1;
3609
3610   if (SDValue Combined = visitORLike(N0, N1, N))
3611     return Combined;
3612
3613   // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3614   SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3615   if (BSwap.getNode())
3616     return BSwap;
3617   BSwap = MatchBSwapHWordLow(N, N0, N1);
3618   if (BSwap.getNode())
3619     return BSwap;
3620
3621   // reassociate or
3622   if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1))
3623     return ROR;
3624   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3625   // iff (c1 & c2) == 0.
3626   if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3627              isa<ConstantSDNode>(N0.getOperand(1))) {
3628     ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3629     if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3630       if (SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N1), VT,
3631                                                    N1C, C1))
3632         return DAG.getNode(
3633             ISD::AND, SDLoc(N), VT,
3634             DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR);
3635       return SDValue();
3636     }
3637   }
3638   // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
3639   if (N0.getOpcode() == N1.getOpcode()) {
3640     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3641     if (Tmp.getNode()) return Tmp;
3642   }
3643
3644   // See if this is some rotate idiom.
3645   if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3646     return SDValue(Rot, 0);
3647
3648   // Simplify the operands using demanded-bits information.
3649   if (!VT.isVector() &&
3650       SimplifyDemandedBits(SDValue(N, 0)))
3651     return SDValue(N, 0);
3652
3653   return SDValue();
3654 }
3655
3656 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
3657 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3658   if (Op.getOpcode() == ISD::AND) {
3659     if (isa<ConstantSDNode>(Op.getOperand(1))) {
3660       Mask = Op.getOperand(1);
3661       Op = Op.getOperand(0);
3662     } else {
3663       return false;
3664     }
3665   }
3666
3667   if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3668     Shift = Op;
3669     return true;
3670   }
3671
3672   return false;
3673 }
3674
3675 // Return true if we can prove that, whenever Neg and Pos are both in the
3676 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos).  This means that
3677 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3678 //
3679 //     (or (shift1 X, Neg), (shift2 X, Pos))
3680 //
3681 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3682 // in direction shift1 by Neg.  The range [0, OpSize) means that we only need
3683 // to consider shift amounts with defined behavior.
3684 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3685   // If OpSize is a power of 2 then:
3686   //
3687   //  (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3688   //  (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3689   //
3690   // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3691   // for the stronger condition:
3692   //
3693   //     Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1)    [A]
3694   //
3695   // for all Neg and Pos.  Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3696   // we can just replace Neg with Neg' for the rest of the function.
3697   //
3698   // In other cases we check for the even stronger condition:
3699   //
3700   //     Neg == OpSize - Pos                                    [B]
3701   //
3702   // for all Neg and Pos.  Note that the (or ...) then invokes undefined
3703   // behavior if Pos == 0 (and consequently Neg == OpSize).
3704   //
3705   // We could actually use [A] whenever OpSize is a power of 2, but the
3706   // only extra cases that it would match are those uninteresting ones
3707   // where Neg and Pos are never in range at the same time.  E.g. for
3708   // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3709   // as well as (sub 32, Pos), but:
3710   //
3711   //     (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3712   //
3713   // always invokes undefined behavior for 32-bit X.
3714   //
3715   // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3716   unsigned MaskLoBits = 0;
3717   if (Neg.getOpcode() == ISD::AND &&
3718       isPowerOf2_64(OpSize) &&
3719       Neg.getOperand(1).getOpcode() == ISD::Constant &&
3720       cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3721     Neg = Neg.getOperand(0);
3722     MaskLoBits = Log2_64(OpSize);
3723   }
3724
3725   // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3726   if (Neg.getOpcode() != ISD::SUB)
3727     return 0;
3728   ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3729   if (!NegC)
3730     return 0;
3731   SDValue NegOp1 = Neg.getOperand(1);
3732
3733   // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3734   // Pos'.  The truncation is redundant for the purpose of the equality.
3735   if (MaskLoBits &&
3736       Pos.getOpcode() == ISD::AND &&
3737       Pos.getOperand(1).getOpcode() == ISD::Constant &&
3738       cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3739     Pos = Pos.getOperand(0);
3740
3741   // The condition we need is now:
3742   //
3743   //     (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3744   //
3745   // If NegOp1 == Pos then we need:
3746   //
3747   //              OpSize & Mask == NegC & Mask
3748   //
3749   // (because "x & Mask" is a truncation and distributes through subtraction).
3750   APInt Width;
3751   if (Pos == NegOp1)
3752     Width = NegC->getAPIntValue();
3753   // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3754   // Then the condition we want to prove becomes:
3755   //
3756   //     (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3757   //
3758   // which, again because "x & Mask" is a truncation, becomes:
3759   //
3760   //                NegC & Mask == (OpSize - PosC) & Mask
3761   //              OpSize & Mask == (NegC + PosC) & Mask
3762   else if (Pos.getOpcode() == ISD::ADD &&
3763            Pos.getOperand(0) == NegOp1 &&
3764            Pos.getOperand(1).getOpcode() == ISD::Constant)
3765     Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3766              NegC->getAPIntValue());
3767   else
3768     return false;
3769
3770   // Now we just need to check that OpSize & Mask == Width & Mask.
3771   if (MaskLoBits)
3772     // Opsize & Mask is 0 since Mask is Opsize - 1.
3773     return Width.getLoBits(MaskLoBits) == 0;
3774   return Width == OpSize;
3775 }
3776
3777 // A subroutine of MatchRotate used once we have found an OR of two opposite
3778 // shifts of Shifted.  If Neg == <operand size> - Pos then the OR reduces
3779 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3780 // former being preferred if supported.  InnerPos and InnerNeg are Pos and
3781 // Neg with outer conversions stripped away.
3782 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3783                                        SDValue Neg, SDValue InnerPos,
3784                                        SDValue InnerNeg, unsigned PosOpcode,
3785                                        unsigned NegOpcode, SDLoc DL) {
3786   // fold (or (shl x, (*ext y)),
3787   //          (srl x, (*ext (sub 32, y)))) ->
3788   //   (rotl x, y) or (rotr x, (sub 32, y))
3789   //
3790   // fold (or (shl x, (*ext (sub 32, y))),
3791   //          (srl x, (*ext y))) ->
3792   //   (rotr x, y) or (rotl x, (sub 32, y))
3793   EVT VT = Shifted.getValueType();
3794   if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3795     bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3796     return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3797                        HasPos ? Pos : Neg).getNode();
3798   }
3799
3800   return nullptr;
3801 }
3802
3803 // MatchRotate - Handle an 'or' of two operands.  If this is one of the many
3804 // idioms for rotate, and if the target supports rotation instructions, generate
3805 // a rot[lr].
3806 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3807   // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
3808   EVT VT = LHS.getValueType();
3809   if (!TLI.isTypeLegal(VT)) return nullptr;
3810
3811   // The target must have at least one rotate flavor.
3812   bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3813   bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3814   if (!HasROTL && !HasROTR) return nullptr;
3815
3816   // Match "(X shl/srl V1) & V2" where V2 may not be present.
3817   SDValue LHSShift;   // The shift.
3818   SDValue LHSMask;    // AND value if any.
3819   if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3820     return nullptr; // Not part of a rotate.
3821
3822   SDValue RHSShift;   // The shift.
3823   SDValue RHSMask;    // AND value if any.
3824   if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3825     return nullptr; // Not part of a rotate.
3826
3827   if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3828     return nullptr;   // Not shifting the same value.
3829
3830   if (LHSShift.getOpcode() == RHSShift.getOpcode())
3831     return nullptr;   // Shifts must disagree.
3832
3833   // Canonicalize shl to left side in a shl/srl pair.
3834   if (RHSShift.getOpcode() == ISD::SHL) {
3835     std::swap(LHS, RHS);
3836     std::swap(LHSShift, RHSShift);
3837     std::swap(LHSMask , RHSMask );
3838   }
3839
3840   unsigned OpSizeInBits = VT.getSizeInBits();
3841   SDValue LHSShiftArg = LHSShift.getOperand(0);
3842   SDValue LHSShiftAmt = LHSShift.getOperand(1);
3843   SDValue RHSShiftArg = RHSShift.getOperand(0);
3844   SDValue RHSShiftAmt = RHSShift.getOperand(1);
3845
3846   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3847   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3848   if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3849       RHSShiftAmt.getOpcode() == ISD::Constant) {
3850     uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3851     uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3852     if ((LShVal + RShVal) != OpSizeInBits)
3853       return nullptr;
3854
3855     SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3856                               LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3857
3858     // If there is an AND of either shifted operand, apply it to the result.
3859     if (LHSMask.getNode() || RHSMask.getNode()) {
3860       APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3861
3862       if (LHSMask.getNode()) {
3863         APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3864         Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3865       }
3866       if (RHSMask.getNode()) {
3867         APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3868         Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3869       }
3870
3871       Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, DL, VT));
3872     }
3873
3874     return Rot.getNode();
3875   }
3876
3877   // If there is a mask here, and we have a variable shift, we can't be sure
3878   // that we're masking out the right stuff.
3879   if (LHSMask.getNode() || RHSMask.getNode())
3880     return nullptr;
3881
3882   // If the shift amount is sign/zext/any-extended just peel it off.
3883   SDValue LExtOp0 = LHSShiftAmt;
3884   SDValue RExtOp0 = RHSShiftAmt;
3885   if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3886        LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3887        LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3888        LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3889       (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3890        RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3891        RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3892        RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3893     LExtOp0 = LHSShiftAmt.getOperand(0);
3894     RExtOp0 = RHSShiftAmt.getOperand(0);
3895   }
3896
3897   SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3898                                    LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3899   if (TryL)
3900     return TryL;
3901
3902   SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3903                                    RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3904   if (TryR)
3905     return TryR;
3906
3907   return nullptr;
3908 }
3909
3910 SDValue DAGCombiner::visitXOR(SDNode *N) {
3911   SDValue N0 = N->getOperand(0);
3912   SDValue N1 = N->getOperand(1);
3913   EVT VT = N0.getValueType();
3914
3915   // fold vector ops
3916   if (VT.isVector()) {
3917     if (SDValue FoldedVOp = SimplifyVBinOp(N))
3918       return FoldedVOp;
3919
3920     // fold (xor x, 0) -> x, vector edition
3921     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3922       return N1;
3923     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3924       return N0;
3925   }
3926
3927   // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3928   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3929     return DAG.getConstant(0, SDLoc(N), VT);
3930   // fold (xor x, undef) -> undef
3931   if (N0.getOpcode() == ISD::UNDEF)
3932     return N0;
3933   if (N1.getOpcode() == ISD::UNDEF)
3934     return N1;
3935   // fold (xor c1, c2) -> c1^c2
3936   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3937   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3938   if (N0C && N1C)
3939     return DAG.FoldConstantArithmetic(ISD::XOR, SDLoc(N), VT, N0C, N1C);
3940   // canonicalize constant to RHS
3941   if (isConstantIntBuildVectorOrConstantInt(N0) &&
3942      !isConstantIntBuildVectorOrConstantInt(N1))
3943     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3944   // fold (xor x, 0) -> x
3945   if (isNullConstant(N1))
3946     return N0;
3947   // reassociate xor
3948   if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1))
3949     return RXOR;
3950
3951   // fold !(x cc y) -> (x !cc y)
3952   SDValue LHS, RHS, CC;
3953   if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3954     bool isInt = LHS.getValueType().isInteger();
3955     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3956                                                isInt);
3957
3958     if (!LegalOperations ||
3959         TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3960       switch (N0.getOpcode()) {
3961       default:
3962         llvm_unreachable("Unhandled SetCC Equivalent!");
3963       case ISD::SETCC:
3964         return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
3965       case ISD::SELECT_CC:
3966         return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
3967                                N0.getOperand(3), NotCC);
3968       }
3969     }
3970   }
3971
3972   // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3973   if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3974       N0.getNode()->hasOneUse() &&
3975       isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3976     SDValue V = N0.getOperand(0);
3977     SDLoc DL(N0);
3978     V = DAG.getNode(ISD::XOR, DL, V.getValueType(), V,
3979                     DAG.getConstant(1, DL, V.getValueType()));
3980     AddToWorklist(V.getNode());
3981     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
3982   }
3983
3984   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3985   if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3986       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3987     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3988     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3989       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3990       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3991       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3992       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
3993       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3994     }
3995   }
3996   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
3997   if (N1C && N1C->isAllOnesValue() &&
3998       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3999     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4000     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
4001       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4002       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4003       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4004       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4005       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4006     }
4007   }
4008   // fold (xor (and x, y), y) -> (and (not x), y)
4009   if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
4010       N0->getOperand(1) == N1) {
4011     SDValue X = N0->getOperand(0);
4012     SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
4013     AddToWorklist(NotX.getNode());
4014     return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
4015   }
4016   // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
4017   if (N1C && N0.getOpcode() == ISD::XOR) {
4018     ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
4019     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
4020     if (N00C) {
4021       SDLoc DL(N);
4022       return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(1),
4023                          DAG.getConstant(N1C->getAPIntValue() ^
4024                                          N00C->getAPIntValue(), DL, VT));
4025     }
4026     if (N01C) {
4027       SDLoc DL(N);
4028       return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(0),
4029                          DAG.getConstant(N1C->getAPIntValue() ^
4030                                          N01C->getAPIntValue(), DL, VT));
4031     }
4032   }
4033   // fold (xor x, x) -> 0
4034   if (N0 == N1)
4035     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
4036
4037   // fold (xor (shl 1, x), -1) -> (rotl ~1, x)
4038   // Here is a concrete example of this equivalence:
4039   // i16   x ==  14
4040   // i16 shl ==   1 << 14  == 16384 == 0b0100000000000000
4041   // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111
4042   //
4043   // =>
4044   //
4045   // i16     ~1      == 0b1111111111111110
4046   // i16 rol(~1, 14) == 0b1011111111111111
4047   //
4048   // Some additional tips to help conceptualize this transform:
4049   // - Try to see the operation as placing a single zero in a value of all ones.
4050   // - There exists no value for x which would allow the result to contain zero.
4051   // - Values of x larger than the bitwidth are undefined and do not require a
4052   //   consistent result.
4053   // - Pushing the zero left requires shifting one bits in from the right.
4054   // A rotate left of ~1 is a nice way of achieving the desired result.
4055   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
4056     if (auto *N1C = dyn_cast<ConstantSDNode>(N1.getNode()))
4057       if (N0.getOpcode() == ISD::SHL)
4058         if (auto *ShlLHS = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
4059           if (N1C->isAllOnesValue() && ShlLHS->isOne()) {
4060             SDLoc DL(N);
4061             return DAG.getNode(ISD::ROTL, DL, VT, DAG.getConstant(~1, DL, VT),
4062                                N0.getOperand(1));
4063           }
4064
4065   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
4066   if (N0.getOpcode() == N1.getOpcode()) {
4067     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
4068     if (Tmp.getNode()) return Tmp;
4069   }
4070
4071   // Simplify the expression using non-local knowledge.
4072   if (!VT.isVector() &&
4073       SimplifyDemandedBits(SDValue(N, 0)))
4074     return SDValue(N, 0);
4075
4076   return SDValue();
4077 }
4078
4079 /// Handle transforms common to the three shifts, when the shift amount is a
4080 /// constant.
4081 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
4082   // We can't and shouldn't fold opaque constants.
4083   if (Amt->isOpaque())
4084     return SDValue();
4085
4086   SDNode *LHS = N->getOperand(0).getNode();
4087   if (!LHS->hasOneUse()) return SDValue();
4088
4089   // We want to pull some binops through shifts, so that we have (and (shift))
4090   // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
4091   // thing happens with address calculations, so it's important to canonicalize
4092   // it.
4093   bool HighBitSet = false;  // Can we transform this if the high bit is set?
4094
4095   switch (LHS->getOpcode()) {
4096   default: return SDValue();
4097   case ISD::OR:
4098   case ISD::XOR:
4099     HighBitSet = false; // We can only transform sra if the high bit is clear.
4100     break;
4101   case ISD::AND:
4102     HighBitSet = true;  // We can only transform sra if the high bit is set.
4103     break;
4104   case ISD::ADD:
4105     if (N->getOpcode() != ISD::SHL)
4106       return SDValue(); // only shl(add) not sr[al](add).
4107     HighBitSet = false; // We can only transform sra if the high bit is clear.
4108     break;
4109   }
4110
4111   // We require the RHS of the binop to be a constant and not opaque as well.
4112   ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
4113   if (!BinOpCst || BinOpCst->isOpaque()) return SDValue();
4114
4115   // FIXME: disable this unless the input to the binop is a shift by a constant.
4116   // If it is not a shift, it pessimizes some common cases like:
4117   //
4118   //    void foo(int *X, int i) { X[i & 1235] = 1; }
4119   //    int bar(int *X, int i) { return X[i & 255]; }
4120   SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
4121   if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
4122        BinOpLHSVal->getOpcode() != ISD::SRA &&
4123        BinOpLHSVal->getOpcode() != ISD::SRL) ||
4124       !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
4125     return SDValue();
4126
4127   EVT VT = N->getValueType(0);
4128
4129   // If this is a signed shift right, and the high bit is modified by the
4130   // logical operation, do not perform the transformation. The highBitSet
4131   // boolean indicates the value of the high bit of the constant which would
4132   // cause it to be modified for this operation.
4133   if (N->getOpcode() == ISD::SRA) {
4134     bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
4135     if (BinOpRHSSignSet != HighBitSet)
4136       return SDValue();
4137   }
4138
4139   if (!TLI.isDesirableToCommuteWithShift(LHS))
4140     return SDValue();
4141
4142   // Fold the constants, shifting the binop RHS by the shift amount.
4143   SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
4144                                N->getValueType(0),
4145                                LHS->getOperand(1), N->getOperand(1));
4146   assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
4147
4148   // Create the new shift.
4149   SDValue NewShift = DAG.getNode(N->getOpcode(),
4150                                  SDLoc(LHS->getOperand(0)),
4151                                  VT, LHS->getOperand(0), N->getOperand(1));
4152
4153   // Create the new binop.
4154   return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
4155 }
4156
4157 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
4158   assert(N->getOpcode() == ISD::TRUNCATE);
4159   assert(N->getOperand(0).getOpcode() == ISD::AND);
4160
4161   // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
4162   if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
4163     SDValue N01 = N->getOperand(0).getOperand(1);
4164
4165     if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
4166       EVT TruncVT = N->getValueType(0);
4167       SDValue N00 = N->getOperand(0).getOperand(0);
4168       APInt TruncC = N01C->getAPIntValue();
4169       TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
4170       SDLoc DL(N);
4171
4172       return DAG.getNode(ISD::AND, DL, TruncVT,
4173                          DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00),
4174                          DAG.getConstant(TruncC, DL, TruncVT));
4175     }
4176   }
4177
4178   return SDValue();
4179 }
4180
4181 SDValue DAGCombiner::visitRotate(SDNode *N) {
4182   // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
4183   if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
4184       N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
4185     SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
4186     if (NewOp1.getNode())
4187       return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
4188                          N->getOperand(0), NewOp1);
4189   }
4190   return SDValue();
4191 }
4192
4193 SDValue DAGCombiner::visitSHL(SDNode *N) {
4194   SDValue N0 = N->getOperand(0);
4195   SDValue N1 = N->getOperand(1);
4196   EVT VT = N0.getValueType();
4197   unsigned OpSizeInBits = VT.getScalarSizeInBits();
4198
4199   // fold vector ops
4200   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4201   if (VT.isVector()) {
4202     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4203       return FoldedVOp;
4204
4205     BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4206     // If setcc produces all-one true value then:
4207     // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
4208     if (N1CV && N1CV->isConstant()) {
4209       if (N0.getOpcode() == ISD::AND) {
4210         SDValue N00 = N0->getOperand(0);
4211         SDValue N01 = N0->getOperand(1);
4212         BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
4213
4214         if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4215             TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4216                 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4217           if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT,
4218                                                      N01CV, N1CV))
4219             return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4220         }
4221       } else {
4222         N1C = isConstOrConstSplat(N1);
4223       }
4224     }
4225   }
4226
4227   // fold (shl c1, c2) -> c1<<c2
4228   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4229   if (N0C && N1C)
4230     return DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, N0C, N1C);
4231   // fold (shl 0, x) -> 0
4232   if (isNullConstant(N0))
4233     return N0;
4234   // fold (shl x, c >= size(x)) -> undef
4235   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4236     return DAG.getUNDEF(VT);
4237   // fold (shl x, 0) -> x
4238   if (N1C && N1C->isNullValue())
4239     return N0;
4240   // fold (shl undef, x) -> 0
4241   if (N0.getOpcode() == ISD::UNDEF)
4242     return DAG.getConstant(0, SDLoc(N), VT);
4243   // if (shl x, c) is known to be zero, return 0
4244   if (DAG.MaskedValueIsZero(SDValue(N, 0),
4245                             APInt::getAllOnesValue(OpSizeInBits)))
4246     return DAG.getConstant(0, SDLoc(N), VT);
4247   // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4248   if (N1.getOpcode() == ISD::TRUNCATE &&
4249       N1.getOperand(0).getOpcode() == ISD::AND) {
4250     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4251     if (NewOp1.getNode())
4252       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4253   }
4254
4255   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4256     return SDValue(N, 0);
4257
4258   // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4259   if (N1C && N0.getOpcode() == ISD::SHL) {
4260     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4261       uint64_t c1 = N0C1->getZExtValue();
4262       uint64_t c2 = N1C->getZExtValue();
4263       SDLoc DL(N);
4264       if (c1 + c2 >= OpSizeInBits)
4265         return DAG.getConstant(0, DL, VT);
4266       return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4267                          DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4268     }
4269   }
4270
4271   // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4272   // For this to be valid, the second form must not preserve any of the bits
4273   // that are shifted out by the inner shift in the first form.  This means
4274   // the outer shift size must be >= the number of bits added by the ext.
4275   // As a corollary, we don't care what kind of ext it is.
4276   if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4277               N0.getOpcode() == ISD::ANY_EXTEND ||
4278               N0.getOpcode() == ISD::SIGN_EXTEND) &&
4279       N0.getOperand(0).getOpcode() == ISD::SHL) {
4280     SDValue N0Op0 = N0.getOperand(0);
4281     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4282       uint64_t c1 = N0Op0C1->getZExtValue();
4283       uint64_t c2 = N1C->getZExtValue();
4284       EVT InnerShiftVT = N0Op0.getValueType();
4285       uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4286       if (c2 >= OpSizeInBits - InnerShiftSize) {
4287         SDLoc DL(N0);
4288         if (c1 + c2 >= OpSizeInBits)
4289           return DAG.getConstant(0, DL, VT);
4290         return DAG.getNode(ISD::SHL, DL, VT,
4291                            DAG.getNode(N0.getOpcode(), DL, VT,
4292                                        N0Op0->getOperand(0)),
4293                            DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4294       }
4295     }
4296   }
4297
4298   // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4299   // Only fold this if the inner zext has no other uses to avoid increasing
4300   // the total number of instructions.
4301   if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4302       N0.getOperand(0).getOpcode() == ISD::SRL) {
4303     SDValue N0Op0 = N0.getOperand(0);
4304     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4305       uint64_t c1 = N0Op0C1->getZExtValue();
4306       if (c1 < VT.getScalarSizeInBits()) {
4307         uint64_t c2 = N1C->getZExtValue();
4308         if (c1 == c2) {
4309           SDValue NewOp0 = N0.getOperand(0);
4310           EVT CountVT = NewOp0.getOperand(1).getValueType();
4311           SDLoc DL(N);
4312           SDValue NewSHL = DAG.getNode(ISD::SHL, DL, NewOp0.getValueType(),
4313                                        NewOp0,
4314                                        DAG.getConstant(c2, DL, CountVT));
4315           AddToWorklist(NewSHL.getNode());
4316           return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4317         }
4318       }
4319     }
4320   }
4321
4322   // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4323   //                               (and (srl x, (sub c1, c2), MASK)
4324   // Only fold this if the inner shift has no other uses -- if it does, folding
4325   // this will increase the total number of instructions.
4326   if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4327     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4328       uint64_t c1 = N0C1->getZExtValue();
4329       if (c1 < OpSizeInBits) {
4330         uint64_t c2 = N1C->getZExtValue();
4331         APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4332         SDValue Shift;
4333         if (c2 > c1) {
4334           Mask = Mask.shl(c2 - c1);
4335           SDLoc DL(N);
4336           Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4337                               DAG.getConstant(c2 - c1, DL, N1.getValueType()));
4338         } else {
4339           Mask = Mask.lshr(c1 - c2);
4340           SDLoc DL(N);
4341           Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4342                               DAG.getConstant(c1 - c2, DL, N1.getValueType()));
4343         }
4344         SDLoc DL(N0);
4345         return DAG.getNode(ISD::AND, DL, VT, Shift,
4346                            DAG.getConstant(Mask, DL, VT));
4347       }
4348     }
4349   }
4350   // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4351   if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4352     unsigned BitSize = VT.getScalarSizeInBits();
4353     SDLoc DL(N);
4354     SDValue HiBitsMask =
4355       DAG.getConstant(APInt::getHighBitsSet(BitSize,
4356                                             BitSize - N1C->getZExtValue()),
4357                       DL, VT);
4358     return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4359                        HiBitsMask);
4360   }
4361
4362   // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
4363   // Variant of version done on multiply, except mul by a power of 2 is turned
4364   // into a shift.
4365   APInt Val;
4366   if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
4367       (isa<ConstantSDNode>(N0.getOperand(1)) ||
4368        isConstantSplatVector(N0.getOperand(1).getNode(), Val))) {
4369     SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
4370     SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
4371     return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
4372   }
4373
4374   if (N1C) {
4375     SDValue NewSHL = visitShiftByConstant(N, N1C);
4376     if (NewSHL.getNode())
4377       return NewSHL;
4378   }
4379
4380   return SDValue();
4381 }
4382
4383 SDValue DAGCombiner::visitSRA(SDNode *N) {
4384   SDValue N0 = N->getOperand(0);
4385   SDValue N1 = N->getOperand(1);
4386   EVT VT = N0.getValueType();
4387   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4388
4389   // fold vector ops
4390   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4391   if (VT.isVector()) {
4392     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4393       return FoldedVOp;
4394
4395     N1C = isConstOrConstSplat(N1);
4396   }
4397
4398   // fold (sra c1, c2) -> (sra c1, c2)
4399   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4400   if (N0C && N1C)
4401     return DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, N0C, N1C);
4402   // fold (sra 0, x) -> 0
4403   if (isNullConstant(N0))
4404     return N0;
4405   // fold (sra -1, x) -> -1
4406   if (N0C && N0C->isAllOnesValue())
4407     return N0;
4408   // fold (sra x, (setge c, size(x))) -> undef
4409   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4410     return DAG.getUNDEF(VT);
4411   // fold (sra x, 0) -> x
4412   if (N1C && N1C->isNullValue())
4413     return N0;
4414   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4415   // sext_inreg.
4416   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4417     unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4418     EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4419     if (VT.isVector())
4420       ExtVT = EVT::getVectorVT(*DAG.getContext(),
4421                                ExtVT, VT.getVectorNumElements());
4422     if ((!LegalOperations ||
4423          TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4424       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4425                          N0.getOperand(0), DAG.getValueType(ExtVT));
4426   }
4427
4428   // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4429   if (N1C && N0.getOpcode() == ISD::SRA) {
4430     if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4431       unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4432       if (Sum >= OpSizeInBits)
4433         Sum = OpSizeInBits - 1;
4434       SDLoc DL(N);
4435       return DAG.getNode(ISD::SRA, DL, VT, N0.getOperand(0),
4436                          DAG.getConstant(Sum, DL, N1.getValueType()));
4437     }
4438   }
4439
4440   // fold (sra (shl X, m), (sub result_size, n))
4441   // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4442   // result_size - n != m.
4443   // If truncate is free for the target sext(shl) is likely to result in better
4444   // code.
4445   if (N0.getOpcode() == ISD::SHL && N1C) {
4446     // Get the two constanst of the shifts, CN0 = m, CN = n.
4447     const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4448     if (N01C) {
4449       LLVMContext &Ctx = *DAG.getContext();
4450       // Determine what the truncate's result bitsize and type would be.
4451       EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4452
4453       if (VT.isVector())
4454         TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4455
4456       // Determine the residual right-shift amount.
4457       signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4458
4459       // If the shift is not a no-op (in which case this should be just a sign
4460       // extend already), the truncated to type is legal, sign_extend is legal
4461       // on that type, and the truncate to that type is both legal and free,
4462       // perform the transform.
4463       if ((ShiftAmt > 0) &&
4464           TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4465           TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4466           TLI.isTruncateFree(VT, TruncVT)) {
4467
4468         SDLoc DL(N);
4469         SDValue Amt = DAG.getConstant(ShiftAmt, DL,
4470             getShiftAmountTy(N0.getOperand(0).getValueType()));
4471         SDValue Shift = DAG.getNode(ISD::SRL, DL, VT,
4472                                     N0.getOperand(0), Amt);
4473         SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT,
4474                                     Shift);
4475         return DAG.getNode(ISD::SIGN_EXTEND, DL,
4476                            N->getValueType(0), Trunc);
4477       }
4478     }
4479   }
4480
4481   // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4482   if (N1.getOpcode() == ISD::TRUNCATE &&
4483       N1.getOperand(0).getOpcode() == ISD::AND) {
4484     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4485     if (NewOp1.getNode())
4486       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4487   }
4488
4489   // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4490   //      if c1 is equal to the number of bits the trunc removes
4491   if (N0.getOpcode() == ISD::TRUNCATE &&
4492       (N0.getOperand(0).getOpcode() == ISD::SRL ||
4493        N0.getOperand(0).getOpcode() == ISD::SRA) &&
4494       N0.getOperand(0).hasOneUse() &&
4495       N0.getOperand(0).getOperand(1).hasOneUse() &&
4496       N1C) {
4497     SDValue N0Op0 = N0.getOperand(0);
4498     if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4499       unsigned LargeShiftVal = LargeShift->getZExtValue();
4500       EVT LargeVT = N0Op0.getValueType();
4501
4502       if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4503         SDLoc DL(N);
4504         SDValue Amt =
4505           DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), DL,
4506                           getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4507         SDValue SRA = DAG.getNode(ISD::SRA, DL, LargeVT,
4508                                   N0Op0.getOperand(0), Amt);
4509         return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA);
4510       }
4511     }
4512   }
4513
4514   // Simplify, based on bits shifted out of the LHS.
4515   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4516     return SDValue(N, 0);
4517
4518
4519   // If the sign bit is known to be zero, switch this to a SRL.
4520   if (DAG.SignBitIsZero(N0))
4521     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4522
4523   if (N1C) {
4524     SDValue NewSRA = visitShiftByConstant(N, N1C);
4525     if (NewSRA.getNode())
4526       return NewSRA;
4527   }
4528
4529   return SDValue();
4530 }
4531
4532 SDValue DAGCombiner::visitSRL(SDNode *N) {
4533   SDValue N0 = N->getOperand(0);
4534   SDValue N1 = N->getOperand(1);
4535   EVT VT = N0.getValueType();
4536   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4537
4538   // fold vector ops
4539   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4540   if (VT.isVector()) {
4541     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4542       return FoldedVOp;
4543
4544     N1C = isConstOrConstSplat(N1);
4545   }
4546
4547   // fold (srl c1, c2) -> c1 >>u c2
4548   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4549   if (N0C && N1C)
4550     return DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, N0C, N1C);
4551   // fold (srl 0, x) -> 0
4552   if (isNullConstant(N0))
4553     return N0;
4554   // fold (srl x, c >= size(x)) -> undef
4555   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4556     return DAG.getUNDEF(VT);
4557   // fold (srl x, 0) -> x
4558   if (N1C && N1C->isNullValue())
4559     return N0;
4560   // if (srl x, c) is known to be zero, return 0
4561   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4562                                    APInt::getAllOnesValue(OpSizeInBits)))
4563     return DAG.getConstant(0, SDLoc(N), VT);
4564
4565   // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4566   if (N1C && N0.getOpcode() == ISD::SRL) {
4567     if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4568       uint64_t c1 = N01C->getZExtValue();
4569       uint64_t c2 = N1C->getZExtValue();
4570       SDLoc DL(N);
4571       if (c1 + c2 >= OpSizeInBits)
4572         return DAG.getConstant(0, DL, VT);
4573       return DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4574                          DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4575     }
4576   }
4577
4578   // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4579   if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4580       N0.getOperand(0).getOpcode() == ISD::SRL &&
4581       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4582     uint64_t c1 =
4583       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4584     uint64_t c2 = N1C->getZExtValue();
4585     EVT InnerShiftVT = N0.getOperand(0).getValueType();
4586     EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4587     uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4588     // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4589     if (c1 + OpSizeInBits == InnerShiftSize) {
4590       SDLoc DL(N0);
4591       if (c1 + c2 >= InnerShiftSize)
4592         return DAG.getConstant(0, DL, VT);
4593       return DAG.getNode(ISD::TRUNCATE, DL, VT,
4594                          DAG.getNode(ISD::SRL, DL, InnerShiftVT,
4595                                      N0.getOperand(0)->getOperand(0),
4596                                      DAG.getConstant(c1 + c2, DL,
4597                                                      ShiftCountVT)));
4598     }
4599   }
4600
4601   // fold (srl (shl x, c), c) -> (and x, cst2)
4602   if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4603     unsigned BitSize = N0.getScalarValueSizeInBits();
4604     if (BitSize <= 64) {
4605       uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4606       SDLoc DL(N);
4607       return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4608                          DAG.getConstant(~0ULL >> ShAmt, DL, VT));
4609     }
4610   }
4611
4612   // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4613   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4614     // Shifting in all undef bits?
4615     EVT SmallVT = N0.getOperand(0).getValueType();
4616     unsigned BitSize = SmallVT.getScalarSizeInBits();
4617     if (N1C->getZExtValue() >= BitSize)
4618       return DAG.getUNDEF(VT);
4619
4620     if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4621       uint64_t ShiftAmt = N1C->getZExtValue();
4622       SDLoc DL0(N0);
4623       SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT,
4624                                        N0.getOperand(0),
4625                           DAG.getConstant(ShiftAmt, DL0,
4626                                           getShiftAmountTy(SmallVT)));
4627       AddToWorklist(SmallShift.getNode());
4628       APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4629       SDLoc DL(N);
4630       return DAG.getNode(ISD::AND, DL, VT,
4631                          DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift),
4632                          DAG.getConstant(Mask, DL, VT));
4633     }
4634   }
4635
4636   // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
4637   // bit, which is unmodified by sra.
4638   if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4639     if (N0.getOpcode() == ISD::SRA)
4640       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4641   }
4642
4643   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
4644   if (N1C && N0.getOpcode() == ISD::CTLZ &&
4645       N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4646     APInt KnownZero, KnownOne;
4647     DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
4648
4649     // If any of the input bits are KnownOne, then the input couldn't be all
4650     // zeros, thus the result of the srl will always be zero.
4651     if (KnownOne.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT);
4652
4653     // If all of the bits input the to ctlz node are known to be zero, then
4654     // the result of the ctlz is "32" and the result of the shift is one.
4655     APInt UnknownBits = ~KnownZero;
4656     if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT);
4657
4658     // Otherwise, check to see if there is exactly one bit input to the ctlz.
4659     if ((UnknownBits & (UnknownBits - 1)) == 0) {
4660       // Okay, we know that only that the single bit specified by UnknownBits
4661       // could be set on input to the CTLZ node. If this bit is set, the SRL
4662       // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4663       // to an SRL/XOR pair, which is likely to simplify more.
4664       unsigned ShAmt = UnknownBits.countTrailingZeros();
4665       SDValue Op = N0.getOperand(0);
4666
4667       if (ShAmt) {
4668         SDLoc DL(N0);
4669         Op = DAG.getNode(ISD::SRL, DL, VT, Op,
4670                   DAG.getConstant(ShAmt, DL,
4671                                   getShiftAmountTy(Op.getValueType())));
4672         AddToWorklist(Op.getNode());
4673       }
4674
4675       SDLoc DL(N);
4676       return DAG.getNode(ISD::XOR, DL, VT,
4677                          Op, DAG.getConstant(1, DL, VT));
4678     }
4679   }
4680
4681   // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4682   if (N1.getOpcode() == ISD::TRUNCATE &&
4683       N1.getOperand(0).getOpcode() == ISD::AND) {
4684     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4685     if (NewOp1.getNode())
4686       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4687   }
4688
4689   // fold operands of srl based on knowledge that the low bits are not
4690   // demanded.
4691   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4692     return SDValue(N, 0);
4693
4694   if (N1C) {
4695     SDValue NewSRL = visitShiftByConstant(N, N1C);
4696     if (NewSRL.getNode())
4697       return NewSRL;
4698   }
4699
4700   // Attempt to convert a srl of a load into a narrower zero-extending load.
4701   SDValue NarrowLoad = ReduceLoadWidth(N);
4702   if (NarrowLoad.getNode())
4703     return NarrowLoad;
4704
4705   // Here is a common situation. We want to optimize:
4706   //
4707   //   %a = ...
4708   //   %b = and i32 %a, 2
4709   //   %c = srl i32 %b, 1
4710   //   brcond i32 %c ...
4711   //
4712   // into
4713   //
4714   //   %a = ...
4715   //   %b = and %a, 2
4716   //   %c = setcc eq %b, 0
4717   //   brcond %c ...
4718   //
4719   // However when after the source operand of SRL is optimized into AND, the SRL
4720   // itself may not be optimized further. Look for it and add the BRCOND into
4721   // the worklist.
4722   if (N->hasOneUse()) {
4723     SDNode *Use = *N->use_begin();
4724     if (Use->getOpcode() == ISD::BRCOND)
4725       AddToWorklist(Use);
4726     else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4727       // Also look pass the truncate.
4728       Use = *Use->use_begin();
4729       if (Use->getOpcode() == ISD::BRCOND)
4730         AddToWorklist(Use);
4731     }
4732   }
4733
4734   return SDValue();
4735 }
4736
4737 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4738   SDValue N0 = N->getOperand(0);
4739   EVT VT = N->getValueType(0);
4740
4741   // fold (ctlz c1) -> c2
4742   if (isa<ConstantSDNode>(N0))
4743     return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4744   return SDValue();
4745 }
4746
4747 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4748   SDValue N0 = N->getOperand(0);
4749   EVT VT = N->getValueType(0);
4750
4751   // fold (ctlz_zero_undef c1) -> c2
4752   if (isa<ConstantSDNode>(N0))
4753     return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4754   return SDValue();
4755 }
4756
4757 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4758   SDValue N0 = N->getOperand(0);
4759   EVT VT = N->getValueType(0);
4760
4761   // fold (cttz c1) -> c2
4762   if (isa<ConstantSDNode>(N0))
4763     return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4764   return SDValue();
4765 }
4766
4767 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4768   SDValue N0 = N->getOperand(0);
4769   EVT VT = N->getValueType(0);
4770
4771   // fold (cttz_zero_undef c1) -> c2
4772   if (isa<ConstantSDNode>(N0))
4773     return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4774   return SDValue();
4775 }
4776
4777 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4778   SDValue N0 = N->getOperand(0);
4779   EVT VT = N->getValueType(0);
4780
4781   // fold (ctpop c1) -> c2
4782   if (isa<ConstantSDNode>(N0))
4783     return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4784   return SDValue();
4785 }
4786
4787
4788 /// \brief Generate Min/Max node
4789 static SDValue combineMinNumMaxNum(SDLoc DL, EVT VT, SDValue LHS, SDValue RHS,
4790                                    SDValue True, SDValue False,
4791                                    ISD::CondCode CC, const TargetLowering &TLI,
4792                                    SelectionDAG &DAG) {
4793   if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
4794     return SDValue();
4795
4796   switch (CC) {
4797   case ISD::SETOLT:
4798   case ISD::SETOLE:
4799   case ISD::SETLT:
4800   case ISD::SETLE:
4801   case ISD::SETULT:
4802   case ISD::SETULE: {
4803     unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM;
4804     if (TLI.isOperationLegal(Opcode, VT))
4805       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4806     return SDValue();
4807   }
4808   case ISD::SETOGT:
4809   case ISD::SETOGE:
4810   case ISD::SETGT:
4811   case ISD::SETGE:
4812   case ISD::SETUGT:
4813   case ISD::SETUGE: {
4814     unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM;
4815     if (TLI.isOperationLegal(Opcode, VT))
4816       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4817     return SDValue();
4818   }
4819   default:
4820     return SDValue();
4821   }
4822 }
4823
4824 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4825   SDValue N0 = N->getOperand(0);
4826   SDValue N1 = N->getOperand(1);
4827   SDValue N2 = N->getOperand(2);
4828   EVT VT = N->getValueType(0);
4829   EVT VT0 = N0.getValueType();
4830
4831   // fold (select C, X, X) -> X
4832   if (N1 == N2)
4833     return N1;
4834   if (const ConstantSDNode *N0C = dyn_cast<const ConstantSDNode>(N0)) {
4835     // fold (select true, X, Y) -> X
4836     // fold (select false, X, Y) -> Y
4837     return !N0C->isNullValue() ? N1 : N2;
4838   }
4839   // fold (select C, 1, X) -> (or C, X)
4840   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4841   if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
4842     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4843   // fold (select C, 0, 1) -> (xor C, 1)
4844   // We can't do this reliably if integer based booleans have different contents
4845   // to floating point based booleans. This is because we can't tell whether we
4846   // have an integer-based boolean or a floating-point-based boolean unless we
4847   // can find the SETCC that produced it and inspect its operands. This is
4848   // fairly easy if C is the SETCC node, but it can potentially be
4849   // undiscoverable (or not reasonably discoverable). For example, it could be
4850   // in another basic block or it could require searching a complicated
4851   // expression.
4852   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4853   if (VT.isInteger() &&
4854       (VT0 == MVT::i1 || (VT0.isInteger() &&
4855                           TLI.getBooleanContents(false, false) ==
4856                               TLI.getBooleanContents(false, true) &&
4857                           TLI.getBooleanContents(false, false) ==
4858                               TargetLowering::ZeroOrOneBooleanContent)) &&
4859       isNullConstant(N1) && N2C && N2C->isOne()) {
4860     SDValue XORNode;
4861     if (VT == VT0) {
4862       SDLoc DL(N);
4863       return DAG.getNode(ISD::XOR, DL, VT0,
4864                          N0, DAG.getConstant(1, DL, VT0));
4865     }
4866     SDLoc DL0(N0);
4867     XORNode = DAG.getNode(ISD::XOR, DL0, VT0,
4868                           N0, DAG.getConstant(1, DL0, VT0));
4869     AddToWorklist(XORNode.getNode());
4870     if (VT.bitsGT(VT0))
4871       return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4872     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4873   }
4874   // fold (select C, 0, X) -> (and (not C), X)
4875   if (VT == VT0 && VT == MVT::i1 && isNullConstant(N1)) {
4876     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4877     AddToWorklist(NOTNode.getNode());
4878     return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4879   }
4880   // fold (select C, X, 1) -> (or (not C), X)
4881   if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4882     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4883     AddToWorklist(NOTNode.getNode());
4884     return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4885   }
4886   // fold (select C, X, 0) -> (and C, X)
4887   if (VT == MVT::i1 && isNullConstant(N2))
4888     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4889   // fold (select X, X, Y) -> (or X, Y)
4890   // fold (select X, 1, Y) -> (or X, Y)
4891   if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4892     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4893   // fold (select X, Y, X) -> (and X, Y)
4894   // fold (select X, Y, 0) -> (and X, Y)
4895   if (VT == MVT::i1 && (N0 == N2 || isNullConstant(N2)))
4896     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4897
4898   // If we can fold this based on the true/false value, do so.
4899   if (SimplifySelectOps(N, N1, N2))
4900     return SDValue(N, 0);  // Don't revisit N.
4901
4902   // fold selects based on a setcc into other things, such as min/max/abs
4903   if (N0.getOpcode() == ISD::SETCC) {
4904     // select x, y (fcmp lt x, y) -> fminnum x, y
4905     // select x, y (fcmp gt x, y) -> fmaxnum x, y
4906     //
4907     // This is OK if we don't care about what happens if either operand is a
4908     // NaN.
4909     //
4910
4911     // FIXME: Instead of testing for UnsafeFPMath, this should be checking for
4912     // no signed zeros as well as no nans.
4913     const TargetOptions &Options = DAG.getTarget().Options;
4914     if (Options.UnsafeFPMath &&
4915         VT.isFloatingPoint() && N0.hasOneUse() &&
4916         DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) {
4917       ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4918
4919       SDValue FMinMax =
4920           combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0), N0.getOperand(1),
4921                               N1, N2, CC, TLI, DAG);
4922       if (FMinMax)
4923         return FMinMax;
4924     }
4925
4926     if ((!LegalOperations &&
4927          TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
4928         TLI.isOperationLegal(ISD::SELECT_CC, VT))
4929       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4930                          N0.getOperand(0), N0.getOperand(1),
4931                          N1, N2, N0.getOperand(2));
4932     return SimplifySelect(SDLoc(N), N0, N1, N2);
4933   }
4934
4935   if (VT0 == MVT::i1) {
4936     if (TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
4937       // select (and Cond0, Cond1), X, Y
4938       //   -> select Cond0, (select Cond1, X, Y), Y
4939       if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) {
4940         SDValue Cond0 = N0->getOperand(0);
4941         SDValue Cond1 = N0->getOperand(1);
4942         SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
4943                                           N1.getValueType(), Cond1, N1, N2);
4944         return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0,
4945                            InnerSelect, N2);
4946       }
4947       // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y)
4948       if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) {
4949         SDValue Cond0 = N0->getOperand(0);
4950         SDValue Cond1 = N0->getOperand(1);
4951         SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
4952                                           N1.getValueType(), Cond1, N1, N2);
4953         return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, N1,
4954                            InnerSelect);
4955       }
4956     }
4957
4958     // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y
4959     if (N1->getOpcode() == ISD::SELECT) {
4960       SDValue N1_0 = N1->getOperand(0);
4961       SDValue N1_1 = N1->getOperand(1);
4962       SDValue N1_2 = N1->getOperand(2);
4963       if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) {
4964         // Create the actual and node if we can generate good code for it.
4965         if (!TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
4966           SDValue And = DAG.getNode(ISD::AND, SDLoc(N), N0.getValueType(),
4967                                     N0, N1_0);
4968           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), And,
4969                              N1_1, N2);
4970         }
4971         // Otherwise see if we can optimize the "and" to a better pattern.
4972         if (SDValue Combined = visitANDLike(N0, N1_0, N))
4973           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
4974                              N1_1, N2);
4975       }
4976     }
4977     // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y
4978     if (N2->getOpcode() == ISD::SELECT) {
4979       SDValue N2_0 = N2->getOperand(0);
4980       SDValue N2_1 = N2->getOperand(1);
4981       SDValue N2_2 = N2->getOperand(2);
4982       if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) {
4983         // Create the actual or node if we can generate good code for it.
4984         if (!TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
4985           SDValue Or = DAG.getNode(ISD::OR, SDLoc(N), N0.getValueType(),
4986                                    N0, N2_0);
4987           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Or,
4988                              N1, N2_2);
4989         }
4990         // Otherwise see if we can optimize to a better pattern.
4991         if (SDValue Combined = visitORLike(N0, N2_0, N))
4992           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
4993                              N1, N2_2);
4994       }
4995     }
4996   }
4997
4998   return SDValue();
4999 }
5000
5001 static
5002 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
5003   SDLoc DL(N);
5004   EVT LoVT, HiVT;
5005   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
5006
5007   // Split the inputs.
5008   SDValue Lo, Hi, LL, LH, RL, RH;
5009   std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
5010   std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
5011
5012   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
5013   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
5014
5015   return std::make_pair(Lo, Hi);
5016 }
5017
5018 // This function assumes all the vselect's arguments are CONCAT_VECTOR
5019 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
5020 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
5021   SDLoc dl(N);
5022   SDValue Cond = N->getOperand(0);
5023   SDValue LHS = N->getOperand(1);
5024   SDValue RHS = N->getOperand(2);
5025   EVT VT = N->getValueType(0);
5026   int NumElems = VT.getVectorNumElements();
5027   assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
5028          RHS.getOpcode() == ISD::CONCAT_VECTORS &&
5029          Cond.getOpcode() == ISD::BUILD_VECTOR);
5030
5031   // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
5032   // binary ones here.
5033   if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
5034     return SDValue();
5035
5036   // We're sure we have an even number of elements due to the
5037   // concat_vectors we have as arguments to vselect.
5038   // Skip BV elements until we find one that's not an UNDEF
5039   // After we find an UNDEF element, keep looping until we get to half the
5040   // length of the BV and see if all the non-undef nodes are the same.
5041   ConstantSDNode *BottomHalf = nullptr;
5042   for (int i = 0; i < NumElems / 2; ++i) {
5043     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
5044       continue;
5045
5046     if (BottomHalf == nullptr)
5047       BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5048     else if (Cond->getOperand(i).getNode() != BottomHalf)
5049       return SDValue();
5050   }
5051
5052   // Do the same for the second half of the BuildVector
5053   ConstantSDNode *TopHalf = nullptr;
5054   for (int i = NumElems / 2; i < NumElems; ++i) {
5055     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
5056       continue;
5057
5058     if (TopHalf == nullptr)
5059       TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5060     else if (Cond->getOperand(i).getNode() != TopHalf)
5061       return SDValue();
5062   }
5063
5064   assert(TopHalf && BottomHalf &&
5065          "One half of the selector was all UNDEFs and the other was all the "
5066          "same value. This should have been addressed before this function.");
5067   return DAG.getNode(
5068       ISD::CONCAT_VECTORS, dl, VT,
5069       BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
5070       TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
5071 }
5072
5073 SDValue DAGCombiner::visitMSCATTER(SDNode *N) {
5074
5075   if (Level >= AfterLegalizeTypes)
5076     return SDValue();
5077
5078   MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(N);
5079   SDValue Mask = MSC->getMask();
5080   SDValue Data  = MSC->getValue();
5081   SDLoc DL(N);
5082
5083   // If the MSCATTER data type requires splitting and the mask is provided by a
5084   // SETCC, then split both nodes and its operands before legalization. This
5085   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5086   // and enables future optimizations (e.g. min/max pattern matching on X86).
5087   if (Mask.getOpcode() != ISD::SETCC)
5088     return SDValue();
5089
5090   // Check if any splitting is required.
5091   if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5092       TargetLowering::TypeSplitVector)
5093     return SDValue();
5094   SDValue MaskLo, MaskHi, Lo, Hi;
5095   std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5096
5097   EVT LoVT, HiVT;
5098   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MSC->getValueType(0));
5099
5100   SDValue Chain = MSC->getChain();
5101
5102   EVT MemoryVT = MSC->getMemoryVT();
5103   unsigned Alignment = MSC->getOriginalAlignment();
5104
5105   EVT LoMemVT, HiMemVT;
5106   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5107
5108   SDValue DataLo, DataHi;
5109   std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5110
5111   SDValue BasePtr = MSC->getBasePtr();
5112   SDValue IndexLo, IndexHi;
5113   std::tie(IndexLo, IndexHi) = DAG.SplitVector(MSC->getIndex(), DL);
5114
5115   MachineMemOperand *MMO = DAG.getMachineFunction().
5116     getMachineMemOperand(MSC->getPointerInfo(), 
5117                           MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
5118                           Alignment, MSC->getAAInfo(), MSC->getRanges());
5119
5120   SDValue OpsLo[] = { Chain, DataLo, MaskLo, BasePtr, IndexLo };
5121   Lo = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataLo.getValueType(),
5122                             DL, OpsLo, MMO);
5123
5124   SDValue OpsHi[] = {Chain, DataHi, MaskHi, BasePtr, IndexHi};
5125   Hi = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataHi.getValueType(),
5126                             DL, OpsHi, MMO);
5127
5128   AddToWorklist(Lo.getNode());
5129   AddToWorklist(Hi.getNode());
5130
5131   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5132 }
5133
5134 SDValue DAGCombiner::visitMSTORE(SDNode *N) {
5135
5136   if (Level >= AfterLegalizeTypes)
5137     return SDValue();
5138
5139   MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N);
5140   SDValue Mask = MST->getMask();
5141   SDValue Data  = MST->getValue();
5142   SDLoc DL(N);
5143
5144   // If the MSTORE data type requires splitting and the mask is provided by a
5145   // SETCC, then split both nodes and its operands before legalization. This
5146   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5147   // and enables future optimizations (e.g. min/max pattern matching on X86).
5148   if (Mask.getOpcode() == ISD::SETCC) {
5149
5150     // Check if any splitting is required.
5151     if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5152         TargetLowering::TypeSplitVector)
5153       return SDValue();
5154
5155     SDValue MaskLo, MaskHi, Lo, Hi;
5156     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5157
5158     EVT LoVT, HiVT;
5159     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MST->getValueType(0));
5160
5161     SDValue Chain = MST->getChain();
5162     SDValue Ptr   = MST->getBasePtr();
5163
5164     EVT MemoryVT = MST->getMemoryVT();
5165     unsigned Alignment = MST->getOriginalAlignment();
5166
5167     // if Alignment is equal to the vector size,
5168     // take the half of it for the second part
5169     unsigned SecondHalfAlignment =
5170       (Alignment == Data->getValueType(0).getSizeInBits()/8) ?
5171          Alignment/2 : Alignment;
5172
5173     EVT LoMemVT, HiMemVT;
5174     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5175
5176     SDValue DataLo, DataHi;
5177     std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5178
5179     MachineMemOperand *MMO = DAG.getMachineFunction().
5180       getMachineMemOperand(MST->getPointerInfo(),
5181                            MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
5182                            Alignment, MST->getAAInfo(), MST->getRanges());
5183
5184     Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO,
5185                             MST->isTruncatingStore());
5186
5187     unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5188     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5189                       DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5190
5191     MMO = DAG.getMachineFunction().
5192       getMachineMemOperand(MST->getPointerInfo(),
5193                            MachineMemOperand::MOStore,  HiMemVT.getStoreSize(),
5194                            SecondHalfAlignment, MST->getAAInfo(),
5195                            MST->getRanges());
5196
5197     Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO,
5198                             MST->isTruncatingStore());
5199
5200     AddToWorklist(Lo.getNode());
5201     AddToWorklist(Hi.getNode());
5202
5203     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5204   }
5205   return SDValue();
5206 }
5207
5208 SDValue DAGCombiner::visitMGATHER(SDNode *N) {
5209
5210   if (Level >= AfterLegalizeTypes)
5211     return SDValue();
5212
5213   MaskedGatherSDNode *MGT = dyn_cast<MaskedGatherSDNode>(N);
5214   SDValue Mask = MGT->getMask();
5215   SDLoc DL(N);
5216
5217   // If the MGATHER result requires splitting and the mask is provided by a
5218   // SETCC, then split both nodes and its operands before legalization. This
5219   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5220   // and enables future optimizations (e.g. min/max pattern matching on X86).
5221
5222   if (Mask.getOpcode() != ISD::SETCC)
5223     return SDValue();
5224
5225   EVT VT = N->getValueType(0);
5226
5227   // Check if any splitting is required.
5228   if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5229       TargetLowering::TypeSplitVector)
5230     return SDValue();
5231
5232   SDValue MaskLo, MaskHi, Lo, Hi;
5233   std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5234
5235   SDValue Src0 = MGT->getValue();
5236   SDValue Src0Lo, Src0Hi;
5237   std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5238
5239   EVT LoVT, HiVT;
5240   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
5241
5242   SDValue Chain = MGT->getChain();
5243   EVT MemoryVT = MGT->getMemoryVT();
5244   unsigned Alignment = MGT->getOriginalAlignment();
5245
5246   EVT LoMemVT, HiMemVT;
5247   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5248
5249   SDValue BasePtr = MGT->getBasePtr();
5250   SDValue Index = MGT->getIndex();
5251   SDValue IndexLo, IndexHi;
5252   std::tie(IndexLo, IndexHi) = DAG.SplitVector(Index, DL);
5253
5254   MachineMemOperand *MMO = DAG.getMachineFunction().
5255     getMachineMemOperand(MGT->getPointerInfo(), 
5256                           MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
5257                           Alignment, MGT->getAAInfo(), MGT->getRanges());
5258
5259   SDValue OpsLo[] = { Chain, Src0Lo, MaskLo, BasePtr, IndexLo };
5260   Lo = DAG.getMaskedGather(DAG.getVTList(LoVT, MVT::Other), LoVT, DL, OpsLo,
5261                             MMO);
5262
5263   SDValue OpsHi[] = {Chain, Src0Hi, MaskHi, BasePtr, IndexHi};
5264   Hi = DAG.getMaskedGather(DAG.getVTList(HiVT, MVT::Other), HiVT, DL, OpsHi,
5265                             MMO);
5266
5267   AddToWorklist(Lo.getNode());
5268   AddToWorklist(Hi.getNode());
5269
5270   // Build a factor node to remember that this load is independent of the
5271   // other one.
5272   Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5273                       Hi.getValue(1));
5274
5275   // Legalized the chain result - switch anything that used the old chain to
5276   // use the new one.
5277   DAG.ReplaceAllUsesOfValueWith(SDValue(MGT, 1), Chain);
5278
5279   SDValue GatherRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5280
5281   SDValue RetOps[] = { GatherRes, Chain };
5282   return DAG.getMergeValues(RetOps, DL);
5283 }
5284
5285 SDValue DAGCombiner::visitMLOAD(SDNode *N) {
5286
5287   if (Level >= AfterLegalizeTypes)
5288     return SDValue();
5289
5290   MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N);
5291   SDValue Mask = MLD->getMask();
5292   SDLoc DL(N);
5293
5294   // If the MLOAD result requires splitting and the mask is provided by a
5295   // SETCC, then split both nodes and its operands before legalization. This
5296   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5297   // and enables future optimizations (e.g. min/max pattern matching on X86).
5298
5299   if (Mask.getOpcode() == ISD::SETCC) {
5300     EVT VT = N->getValueType(0);
5301
5302     // Check if any splitting is required.
5303     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5304         TargetLowering::TypeSplitVector)
5305       return SDValue();
5306
5307     SDValue MaskLo, MaskHi, Lo, Hi;
5308     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5309
5310     SDValue Src0 = MLD->getSrc0();
5311     SDValue Src0Lo, Src0Hi;
5312     std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5313
5314     EVT LoVT, HiVT;
5315     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0));
5316
5317     SDValue Chain = MLD->getChain();
5318     SDValue Ptr   = MLD->getBasePtr();
5319     EVT MemoryVT = MLD->getMemoryVT();
5320     unsigned Alignment = MLD->getOriginalAlignment();
5321
5322     // if Alignment is equal to the vector size,
5323     // take the half of it for the second part
5324     unsigned SecondHalfAlignment =
5325       (Alignment == MLD->getValueType(0).getSizeInBits()/8) ?
5326          Alignment/2 : Alignment;
5327
5328     EVT LoMemVT, HiMemVT;
5329     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5330
5331     MachineMemOperand *MMO = DAG.getMachineFunction().
5332     getMachineMemOperand(MLD->getPointerInfo(),
5333                          MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
5334                          Alignment, MLD->getAAInfo(), MLD->getRanges());
5335
5336     Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO,
5337                            ISD::NON_EXTLOAD);
5338
5339     unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5340     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5341                       DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5342
5343     MMO = DAG.getMachineFunction().
5344     getMachineMemOperand(MLD->getPointerInfo(),
5345                          MachineMemOperand::MOLoad,  HiMemVT.getStoreSize(),
5346                          SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges());
5347
5348     Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO,
5349                            ISD::NON_EXTLOAD);
5350
5351     AddToWorklist(Lo.getNode());
5352     AddToWorklist(Hi.getNode());
5353
5354     // Build a factor node to remember that this load is independent of the
5355     // other one.
5356     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5357                         Hi.getValue(1));
5358
5359     // Legalized the chain result - switch anything that used the old chain to
5360     // use the new one.
5361     DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain);
5362
5363     SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5364
5365     SDValue RetOps[] = { LoadRes, Chain };
5366     return DAG.getMergeValues(RetOps, DL);
5367   }
5368   return SDValue();
5369 }
5370
5371 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
5372   SDValue N0 = N->getOperand(0);
5373   SDValue N1 = N->getOperand(1);
5374   SDValue N2 = N->getOperand(2);
5375   SDLoc DL(N);
5376
5377   // Canonicalize integer abs.
5378   // vselect (setg[te] X,  0),  X, -X ->
5379   // vselect (setgt    X, -1),  X, -X ->
5380   // vselect (setl[te] X,  0), -X,  X ->
5381   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5382   if (N0.getOpcode() == ISD::SETCC) {
5383     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5384     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5385     bool isAbs = false;
5386     bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
5387
5388     if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
5389          (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
5390         N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
5391       isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
5392     else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
5393              N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
5394       isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
5395
5396     if (isAbs) {
5397       EVT VT = LHS.getValueType();
5398       SDValue Shift = DAG.getNode(
5399           ISD::SRA, DL, VT, LHS,
5400           DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, DL, VT));
5401       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
5402       AddToWorklist(Shift.getNode());
5403       AddToWorklist(Add.getNode());
5404       return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
5405     }
5406   }
5407
5408   if (SimplifySelectOps(N, N1, N2))
5409     return SDValue(N, 0);  // Don't revisit N.
5410
5411   // If the VSELECT result requires splitting and the mask is provided by a
5412   // SETCC, then split both nodes and its operands before legalization. This
5413   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5414   // and enables future optimizations (e.g. min/max pattern matching on X86).
5415   if (N0.getOpcode() == ISD::SETCC) {
5416     EVT VT = N->getValueType(0);
5417
5418     // Check if any splitting is required.
5419     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5420         TargetLowering::TypeSplitVector)
5421       return SDValue();
5422
5423     SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
5424     std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
5425     std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
5426     std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
5427
5428     Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
5429     Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
5430
5431     // Add the new VSELECT nodes to the work list in case they need to be split
5432     // again.
5433     AddToWorklist(Lo.getNode());
5434     AddToWorklist(Hi.getNode());
5435
5436     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5437   }
5438
5439   // Fold (vselect (build_vector all_ones), N1, N2) -> N1
5440   if (ISD::isBuildVectorAllOnes(N0.getNode()))
5441     return N1;
5442   // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
5443   if (ISD::isBuildVectorAllZeros(N0.getNode()))
5444     return N2;
5445
5446   // The ConvertSelectToConcatVector function is assuming both the above
5447   // checks for (vselect (build_vector all{ones,zeros) ...) have been made
5448   // and addressed.
5449   if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
5450       N2.getOpcode() == ISD::CONCAT_VECTORS &&
5451       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5452     SDValue CV = ConvertSelectToConcatVector(N, DAG);
5453     if (CV.getNode())
5454       return CV;
5455   }
5456
5457   return SDValue();
5458 }
5459
5460 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
5461   SDValue N0 = N->getOperand(0);
5462   SDValue N1 = N->getOperand(1);
5463   SDValue N2 = N->getOperand(2);
5464   SDValue N3 = N->getOperand(3);
5465   SDValue N4 = N->getOperand(4);
5466   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
5467
5468   // fold select_cc lhs, rhs, x, x, cc -> x
5469   if (N2 == N3)
5470     return N2;
5471
5472   // Determine if the condition we're dealing with is constant
5473   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
5474                               N0, N1, CC, SDLoc(N), false);
5475   if (SCC.getNode()) {
5476     AddToWorklist(SCC.getNode());
5477
5478     if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
5479       if (!SCCC->isNullValue())
5480         return N2;    // cond always true -> true val
5481       else
5482         return N3;    // cond always false -> false val
5483     } else if (SCC->getOpcode() == ISD::UNDEF) {
5484       // When the condition is UNDEF, just return the first operand. This is
5485       // coherent the DAG creation, no setcc node is created in this case
5486       return N2;
5487     } else if (SCC.getOpcode() == ISD::SETCC) {
5488       // Fold to a simpler select_cc
5489       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
5490                          SCC.getOperand(0), SCC.getOperand(1), N2, N3,
5491                          SCC.getOperand(2));
5492     }
5493   }
5494
5495   // If we can fold this based on the true/false value, do so.
5496   if (SimplifySelectOps(N, N2, N3))
5497     return SDValue(N, 0);  // Don't revisit N.
5498
5499   // fold select_cc into other things, such as min/max/abs
5500   return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
5501 }
5502
5503 SDValue DAGCombiner::visitSETCC(SDNode *N) {
5504   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
5505                        cast<CondCodeSDNode>(N->getOperand(2))->get(),
5506                        SDLoc(N));
5507 }
5508
5509 // tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
5510 // dag node into a ConstantSDNode or a build_vector of constants.
5511 // This function is called by the DAGCombiner when visiting sext/zext/aext
5512 // dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
5513 // Vector extends are not folded if operations are legal; this is to
5514 // avoid introducing illegal build_vector dag nodes.
5515 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
5516                                          SelectionDAG &DAG, bool LegalTypes,
5517                                          bool LegalOperations) {
5518   unsigned Opcode = N->getOpcode();
5519   SDValue N0 = N->getOperand(0);
5520   EVT VT = N->getValueType(0);
5521
5522   assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
5523          Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
5524
5525   // fold (sext c1) -> c1
5526   // fold (zext c1) -> c1
5527   // fold (aext c1) -> c1
5528   if (isa<ConstantSDNode>(N0))
5529     return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
5530
5531   // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
5532   // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
5533   // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
5534   EVT SVT = VT.getScalarType();
5535   if (!(VT.isVector() &&
5536       (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
5537       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
5538     return nullptr;
5539
5540   // We can fold this node into a build_vector.
5541   unsigned VTBits = SVT.getSizeInBits();
5542   unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
5543   unsigned ShAmt = VTBits - EVTBits;
5544   SmallVector<SDValue, 8> Elts;
5545   unsigned NumElts = N0->getNumOperands();
5546   SDLoc DL(N);
5547
5548   for (unsigned i=0; i != NumElts; ++i) {
5549     SDValue Op = N0->getOperand(i);
5550     if (Op->getOpcode() == ISD::UNDEF) {
5551       Elts.push_back(DAG.getUNDEF(SVT));
5552       continue;
5553     }
5554
5555     SDLoc DL(Op);
5556     ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
5557     const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
5558     if (Opcode == ISD::SIGN_EXTEND)
5559       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
5560                                      DL, SVT));
5561     else
5562       Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
5563                                      DL, SVT));
5564   }
5565
5566   return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
5567 }
5568
5569 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
5570 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
5571 // transformation. Returns true if extension are possible and the above
5572 // mentioned transformation is profitable.
5573 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
5574                                     unsigned ExtOpc,
5575                                     SmallVectorImpl<SDNode *> &ExtendNodes,
5576                                     const TargetLowering &TLI) {
5577   bool HasCopyToRegUses = false;
5578   bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
5579   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
5580                             UE = N0.getNode()->use_end();
5581        UI != UE; ++UI) {
5582     SDNode *User = *UI;
5583     if (User == N)
5584       continue;
5585     if (UI.getUse().getResNo() != N0.getResNo())
5586       continue;
5587     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
5588     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
5589       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
5590       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
5591         // Sign bits will be lost after a zext.
5592         return false;
5593       bool Add = false;
5594       for (unsigned i = 0; i != 2; ++i) {
5595         SDValue UseOp = User->getOperand(i);
5596         if (UseOp == N0)
5597           continue;
5598         if (!isa<ConstantSDNode>(UseOp))
5599           return false;
5600         Add = true;
5601       }
5602       if (Add)
5603         ExtendNodes.push_back(User);
5604       continue;
5605     }
5606     // If truncates aren't free and there are users we can't
5607     // extend, it isn't worthwhile.
5608     if (!isTruncFree)
5609       return false;
5610     // Remember if this value is live-out.
5611     if (User->getOpcode() == ISD::CopyToReg)
5612       HasCopyToRegUses = true;
5613   }
5614
5615   if (HasCopyToRegUses) {
5616     bool BothLiveOut = false;
5617     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
5618          UI != UE; ++UI) {
5619       SDUse &Use = UI.getUse();
5620       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
5621         BothLiveOut = true;
5622         break;
5623       }
5624     }
5625     if (BothLiveOut)
5626       // Both unextended and extended values are live out. There had better be
5627       // a good reason for the transformation.
5628       return ExtendNodes.size();
5629   }
5630   return true;
5631 }
5632
5633 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
5634                                   SDValue Trunc, SDValue ExtLoad, SDLoc DL,
5635                                   ISD::NodeType ExtType) {
5636   // Extend SetCC uses if necessary.
5637   for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
5638     SDNode *SetCC = SetCCs[i];
5639     SmallVector<SDValue, 4> Ops;
5640
5641     for (unsigned j = 0; j != 2; ++j) {
5642       SDValue SOp = SetCC->getOperand(j);
5643       if (SOp == Trunc)
5644         Ops.push_back(ExtLoad);
5645       else
5646         Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
5647     }
5648
5649     Ops.push_back(SetCC->getOperand(2));
5650     CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
5651   }
5652 }
5653
5654 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?).
5655 SDValue DAGCombiner::CombineExtLoad(SDNode *N) {
5656   SDValue N0 = N->getOperand(0);
5657   EVT DstVT = N->getValueType(0);
5658   EVT SrcVT = N0.getValueType();
5659
5660   assert((N->getOpcode() == ISD::SIGN_EXTEND ||
5661           N->getOpcode() == ISD::ZERO_EXTEND) &&
5662          "Unexpected node type (not an extend)!");
5663
5664   // fold (sext (load x)) to multiple smaller sextloads; same for zext.
5665   // For example, on a target with legal v4i32, but illegal v8i32, turn:
5666   //   (v8i32 (sext (v8i16 (load x))))
5667   // into:
5668   //   (v8i32 (concat_vectors (v4i32 (sextload x)),
5669   //                          (v4i32 (sextload (x + 16)))))
5670   // Where uses of the original load, i.e.:
5671   //   (v8i16 (load x))
5672   // are replaced with:
5673   //   (v8i16 (truncate
5674   //     (v8i32 (concat_vectors (v4i32 (sextload x)),
5675   //                            (v4i32 (sextload (x + 16)))))))
5676   //
5677   // This combine is only applicable to illegal, but splittable, vectors.
5678   // All legal types, and illegal non-vector types, are handled elsewhere.
5679   // This combine is controlled by TargetLowering::isVectorLoadExtDesirable.
5680   //
5681   if (N0->getOpcode() != ISD::LOAD)
5682     return SDValue();
5683
5684   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5685
5686   if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) ||
5687       !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() ||
5688       !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0)))
5689     return SDValue();
5690
5691   SmallVector<SDNode *, 4> SetCCs;
5692   if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI))
5693     return SDValue();
5694
5695   ISD::LoadExtType ExtType =
5696       N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
5697
5698   // Try to split the vector types to get down to legal types.
5699   EVT SplitSrcVT = SrcVT;
5700   EVT SplitDstVT = DstVT;
5701   while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) &&
5702          SplitSrcVT.getVectorNumElements() > 1) {
5703     SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first;
5704     SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first;
5705   }
5706
5707   if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT))
5708     return SDValue();
5709
5710   SDLoc DL(N);
5711   const unsigned NumSplits =
5712       DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements();
5713   const unsigned Stride = SplitSrcVT.getStoreSize();
5714   SmallVector<SDValue, 4> Loads;
5715   SmallVector<SDValue, 4> Chains;
5716
5717   SDValue BasePtr = LN0->getBasePtr();
5718   for (unsigned Idx = 0; Idx < NumSplits; Idx++) {
5719     const unsigned Offset = Idx * Stride;
5720     const unsigned Align = MinAlign(LN0->getAlignment(), Offset);
5721
5722     SDValue SplitLoad = DAG.getExtLoad(
5723         ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr,
5724         LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT,
5725         LN0->isVolatile(), LN0->isNonTemporal(), LN0->isInvariant(),
5726         Align, LN0->getAAInfo());
5727
5728     BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
5729                           DAG.getConstant(Stride, DL, BasePtr.getValueType()));
5730
5731     Loads.push_back(SplitLoad.getValue(0));
5732     Chains.push_back(SplitLoad.getValue(1));
5733   }
5734
5735   SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
5736   SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads);
5737
5738   CombineTo(N, NewValue);
5739
5740   // Replace uses of the original load (before extension)
5741   // with a truncate of the concatenated sextloaded vectors.
5742   SDValue Trunc =
5743       DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue);
5744   CombineTo(N0.getNode(), Trunc, NewChain);
5745   ExtendSetCCUses(SetCCs, Trunc, NewValue, DL,
5746                   (ISD::NodeType)N->getOpcode());
5747   return SDValue(N, 0); // Return N so it doesn't get rechecked!
5748 }
5749
5750 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
5751   SDValue N0 = N->getOperand(0);
5752   EVT VT = N->getValueType(0);
5753
5754   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5755                                               LegalOperations))
5756     return SDValue(Res, 0);
5757
5758   // fold (sext (sext x)) -> (sext x)
5759   // fold (sext (aext x)) -> (sext x)
5760   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5761     return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
5762                        N0.getOperand(0));
5763
5764   if (N0.getOpcode() == ISD::TRUNCATE) {
5765     // fold (sext (truncate (load x))) -> (sext (smaller load x))
5766     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
5767     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5768     if (NarrowLoad.getNode()) {
5769       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5770       if (NarrowLoad.getNode() != N0.getNode()) {
5771         CombineTo(N0.getNode(), NarrowLoad);
5772         // CombineTo deleted the truncate, if needed, but not what's under it.
5773         AddToWorklist(oye);
5774       }
5775       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5776     }
5777
5778     // See if the value being truncated is already sign extended.  If so, just
5779     // eliminate the trunc/sext pair.
5780     SDValue Op = N0.getOperand(0);
5781     unsigned OpBits   = Op.getValueType().getScalarType().getSizeInBits();
5782     unsigned MidBits  = N0.getValueType().getScalarType().getSizeInBits();
5783     unsigned DestBits = VT.getScalarType().getSizeInBits();
5784     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
5785
5786     if (OpBits == DestBits) {
5787       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
5788       // bits, it is already ready.
5789       if (NumSignBits > DestBits-MidBits)
5790         return Op;
5791     } else if (OpBits < DestBits) {
5792       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
5793       // bits, just sext from i32.
5794       if (NumSignBits > OpBits-MidBits)
5795         return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
5796     } else {
5797       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
5798       // bits, just truncate to i32.
5799       if (NumSignBits > OpBits-MidBits)
5800         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5801     }
5802
5803     // fold (sext (truncate x)) -> (sextinreg x).
5804     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
5805                                                  N0.getValueType())) {
5806       if (OpBits < DestBits)
5807         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
5808       else if (OpBits > DestBits)
5809         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
5810       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
5811                          DAG.getValueType(N0.getValueType()));
5812     }
5813   }
5814
5815   // fold (sext (load x)) -> (sext (truncate (sextload x)))
5816   // Only generate vector extloads when 1) they're legal, and 2) they are
5817   // deemed desirable by the target.
5818   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5819       ((!LegalOperations && !VT.isVector() &&
5820         !cast<LoadSDNode>(N0)->isVolatile()) ||
5821        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) {
5822     bool DoXform = true;
5823     SmallVector<SDNode*, 4> SetCCs;
5824     if (!N0.hasOneUse())
5825       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
5826     if (VT.isVector())
5827       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
5828     if (DoXform) {
5829       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5830       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5831                                        LN0->getChain(),
5832                                        LN0->getBasePtr(), N0.getValueType(),
5833                                        LN0->getMemOperand());
5834       CombineTo(N, ExtLoad);
5835       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5836                                   N0.getValueType(), ExtLoad);
5837       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5838       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5839                       ISD::SIGN_EXTEND);
5840       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5841     }
5842   }
5843
5844   // fold (sext (load x)) to multiple smaller sextloads.
5845   // Only on illegal but splittable vectors.
5846   if (SDValue ExtLoad = CombineExtLoad(N))
5847     return ExtLoad;
5848
5849   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
5850   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
5851   if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5852       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5853     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5854     EVT MemVT = LN0->getMemoryVT();
5855     if ((!LegalOperations && !LN0->isVolatile()) ||
5856         TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) {
5857       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5858                                        LN0->getChain(),
5859                                        LN0->getBasePtr(), MemVT,
5860                                        LN0->getMemOperand());
5861       CombineTo(N, ExtLoad);
5862       CombineTo(N0.getNode(),
5863                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5864                             N0.getValueType(), ExtLoad),
5865                 ExtLoad.getValue(1));
5866       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5867     }
5868   }
5869
5870   // fold (sext (and/or/xor (load x), cst)) ->
5871   //      (and/or/xor (sextload x), (sext cst))
5872   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5873        N0.getOpcode() == ISD::XOR) &&
5874       isa<LoadSDNode>(N0.getOperand(0)) &&
5875       N0.getOperand(1).getOpcode() == ISD::Constant &&
5876       TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) &&
5877       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5878     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5879     if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
5880       bool DoXform = true;
5881       SmallVector<SDNode*, 4> SetCCs;
5882       if (!N0.hasOneUse())
5883         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
5884                                           SetCCs, TLI);
5885       if (DoXform) {
5886         SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
5887                                          LN0->getChain(), LN0->getBasePtr(),
5888                                          LN0->getMemoryVT(),
5889                                          LN0->getMemOperand());
5890         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5891         Mask = Mask.sext(VT.getSizeInBits());
5892         SDLoc DL(N);
5893         SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
5894                                   ExtLoad, DAG.getConstant(Mask, DL, VT));
5895         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5896                                     SDLoc(N0.getOperand(0)),
5897                                     N0.getOperand(0).getValueType(), ExtLoad);
5898         CombineTo(N, And);
5899         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5900         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
5901                         ISD::SIGN_EXTEND);
5902         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5903       }
5904     }
5905   }
5906
5907   if (N0.getOpcode() == ISD::SETCC) {
5908     EVT N0VT = N0.getOperand(0).getValueType();
5909     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
5910     // Only do this before legalize for now.
5911     if (VT.isVector() && !LegalOperations &&
5912         TLI.getBooleanContents(N0VT) ==
5913             TargetLowering::ZeroOrNegativeOneBooleanContent) {
5914       // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5915       // of the same size as the compared operands. Only optimize sext(setcc())
5916       // if this is the case.
5917       EVT SVT = getSetCCResultType(N0VT);
5918
5919       // We know that the # elements of the results is the same as the
5920       // # elements of the compare (and the # elements of the compare result
5921       // for that matter).  Check to see that they are the same size.  If so,
5922       // we know that the element size of the sext'd result matches the
5923       // element size of the compare operands.
5924       if (VT.getSizeInBits() == SVT.getSizeInBits())
5925         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5926                              N0.getOperand(1),
5927                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
5928
5929       // If the desired elements are smaller or larger than the source
5930       // elements we can use a matching integer vector type and then
5931       // truncate/sign extend
5932       EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5933       if (SVT == MatchingVectorType) {
5934         SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
5935                                N0.getOperand(0), N0.getOperand(1),
5936                                cast<CondCodeSDNode>(N0.getOperand(2))->get());
5937         return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5938       }
5939     }
5940
5941     // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
5942     unsigned ElementWidth = VT.getScalarType().getSizeInBits();
5943     SDLoc DL(N);
5944     SDValue NegOne =
5945       DAG.getConstant(APInt::getAllOnesValue(ElementWidth), DL, VT);
5946     SDValue SCC =
5947       SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
5948                        NegOne, DAG.getConstant(0, DL, VT),
5949                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5950     if (SCC.getNode()) return SCC;
5951
5952     if (!VT.isVector()) {
5953       EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
5954       if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
5955         SDLoc DL(N);
5956         ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5957         SDValue SetCC = DAG.getSetCC(DL, SetCCVT,
5958                                      N0.getOperand(0), N0.getOperand(1), CC);
5959         return DAG.getSelect(DL, VT, SetCC,
5960                              NegOne, DAG.getConstant(0, DL, VT));
5961       }
5962     }
5963   }
5964
5965   // fold (sext x) -> (zext x) if the sign bit is known zero.
5966   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
5967       DAG.SignBitIsZero(N0))
5968     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
5969
5970   return SDValue();
5971 }
5972
5973 // isTruncateOf - If N is a truncate of some other value, return true, record
5974 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
5975 // This function computes KnownZero to avoid a duplicated call to
5976 // computeKnownBits in the caller.
5977 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
5978                          APInt &KnownZero) {
5979   APInt KnownOne;
5980   if (N->getOpcode() == ISD::TRUNCATE) {
5981     Op = N->getOperand(0);
5982     DAG.computeKnownBits(Op, KnownZero, KnownOne);
5983     return true;
5984   }
5985
5986   if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
5987       cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
5988     return false;
5989
5990   SDValue Op0 = N->getOperand(0);
5991   SDValue Op1 = N->getOperand(1);
5992   assert(Op0.getValueType() == Op1.getValueType());
5993
5994   if (isNullConstant(Op0))
5995     Op = Op1;
5996   else if (isNullConstant(Op1))
5997     Op = Op0;
5998   else
5999     return false;
6000
6001   DAG.computeKnownBits(Op, KnownZero, KnownOne);
6002
6003   if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
6004     return false;
6005
6006   return true;
6007 }
6008
6009 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
6010   SDValue N0 = N->getOperand(0);
6011   EVT VT = N->getValueType(0);
6012
6013   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6014                                               LegalOperations))
6015     return SDValue(Res, 0);
6016
6017   // fold (zext (zext x)) -> (zext x)
6018   // fold (zext (aext x)) -> (zext x)
6019   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
6020     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
6021                        N0.getOperand(0));
6022
6023   // fold (zext (truncate x)) -> (zext x) or
6024   //      (zext (truncate x)) -> (truncate x)
6025   // This is valid when the truncated bits of x are already zero.
6026   // FIXME: We should extend this to work for vectors too.
6027   SDValue Op;
6028   APInt KnownZero;
6029   if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
6030     APInt TruncatedBits =
6031       (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
6032       APInt(Op.getValueSizeInBits(), 0) :
6033       APInt::getBitsSet(Op.getValueSizeInBits(),
6034                         N0.getValueSizeInBits(),
6035                         std::min(Op.getValueSizeInBits(),
6036                                  VT.getSizeInBits()));
6037     if (TruncatedBits == (KnownZero & TruncatedBits)) {
6038       if (VT.bitsGT(Op.getValueType()))
6039         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
6040       if (VT.bitsLT(Op.getValueType()))
6041         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6042
6043       return Op;
6044     }
6045   }
6046
6047   // fold (zext (truncate (load x))) -> (zext (smaller load x))
6048   // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
6049   if (N0.getOpcode() == ISD::TRUNCATE) {
6050     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
6051     if (NarrowLoad.getNode()) {
6052       SDNode* oye = N0.getNode()->getOperand(0).getNode();
6053       if (NarrowLoad.getNode() != N0.getNode()) {
6054         CombineTo(N0.getNode(), NarrowLoad);
6055         // CombineTo deleted the truncate, if needed, but not what's under it.
6056         AddToWorklist(oye);
6057       }
6058       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6059     }
6060   }
6061
6062   // fold (zext (truncate x)) -> (and x, mask)
6063   if (N0.getOpcode() == ISD::TRUNCATE &&
6064       (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
6065
6066     // fold (zext (truncate (load x))) -> (zext (smaller load x))
6067     // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
6068     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
6069     if (NarrowLoad.getNode()) {
6070       SDNode* oye = N0.getNode()->getOperand(0).getNode();
6071       if (NarrowLoad.getNode() != N0.getNode()) {
6072         CombineTo(N0.getNode(), NarrowLoad);
6073         // CombineTo deleted the truncate, if needed, but not what's under it.
6074         AddToWorklist(oye);
6075       }
6076       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6077     }
6078
6079     SDValue Op = N0.getOperand(0);
6080     if (Op.getValueType().bitsLT(VT)) {
6081       Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
6082       AddToWorklist(Op.getNode());
6083     } else if (Op.getValueType().bitsGT(VT)) {
6084       Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6085       AddToWorklist(Op.getNode());
6086     }
6087     return DAG.getZeroExtendInReg(Op, SDLoc(N),
6088                                   N0.getValueType().getScalarType());
6089   }
6090
6091   // Fold (zext (and (trunc x), cst)) -> (and x, cst),
6092   // if either of the casts is not free.
6093   if (N0.getOpcode() == ISD::AND &&
6094       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6095       N0.getOperand(1).getOpcode() == ISD::Constant &&
6096       (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6097                            N0.getValueType()) ||
6098        !TLI.isZExtFree(N0.getValueType(), VT))) {
6099     SDValue X = N0.getOperand(0).getOperand(0);
6100     if (X.getValueType().bitsLT(VT)) {
6101       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
6102     } else if (X.getValueType().bitsGT(VT)) {
6103       X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6104     }
6105     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6106     Mask = Mask.zext(VT.getSizeInBits());
6107     SDLoc DL(N);
6108     return DAG.getNode(ISD::AND, DL, VT,
6109                        X, DAG.getConstant(Mask, DL, VT));
6110   }
6111
6112   // fold (zext (load x)) -> (zext (truncate (zextload x)))
6113   // Only generate vector extloads when 1) they're legal, and 2) they are
6114   // deemed desirable by the target.
6115   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6116       ((!LegalOperations && !VT.isVector() &&
6117         !cast<LoadSDNode>(N0)->isVolatile()) ||
6118        TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) {
6119     bool DoXform = true;
6120     SmallVector<SDNode*, 4> SetCCs;
6121     if (!N0.hasOneUse())
6122       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
6123     if (VT.isVector())
6124       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
6125     if (DoXform) {
6126       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6127       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6128                                        LN0->getChain(),
6129                                        LN0->getBasePtr(), N0.getValueType(),
6130                                        LN0->getMemOperand());
6131       CombineTo(N, ExtLoad);
6132       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6133                                   N0.getValueType(), ExtLoad);
6134       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6135
6136       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6137                       ISD::ZERO_EXTEND);
6138       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6139     }
6140   }
6141
6142   // fold (zext (load x)) to multiple smaller zextloads.
6143   // Only on illegal but splittable vectors.
6144   if (SDValue ExtLoad = CombineExtLoad(N))
6145     return ExtLoad;
6146
6147   // fold (zext (and/or/xor (load x), cst)) ->
6148   //      (and/or/xor (zextload x), (zext cst))
6149   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
6150        N0.getOpcode() == ISD::XOR) &&
6151       isa<LoadSDNode>(N0.getOperand(0)) &&
6152       N0.getOperand(1).getOpcode() == ISD::Constant &&
6153       TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) &&
6154       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
6155     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
6156     if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
6157       bool DoXform = true;
6158       SmallVector<SDNode*, 4> SetCCs;
6159       if (!N0.hasOneUse())
6160         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
6161                                           SetCCs, TLI);
6162       if (DoXform) {
6163         SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
6164                                          LN0->getChain(), LN0->getBasePtr(),
6165                                          LN0->getMemoryVT(),
6166                                          LN0->getMemOperand());
6167         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6168         Mask = Mask.zext(VT.getSizeInBits());
6169         SDLoc DL(N);
6170         SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
6171                                   ExtLoad, DAG.getConstant(Mask, DL, VT));
6172         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
6173                                     SDLoc(N0.getOperand(0)),
6174                                     N0.getOperand(0).getValueType(), ExtLoad);
6175         CombineTo(N, And);
6176         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
6177         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
6178                         ISD::ZERO_EXTEND);
6179         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6180       }
6181     }
6182   }
6183
6184   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
6185   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
6186   if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
6187       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
6188     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6189     EVT MemVT = LN0->getMemoryVT();
6190     if ((!LegalOperations && !LN0->isVolatile()) ||
6191         TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) {
6192       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6193                                        LN0->getChain(),
6194                                        LN0->getBasePtr(), MemVT,
6195                                        LN0->getMemOperand());
6196       CombineTo(N, ExtLoad);
6197       CombineTo(N0.getNode(),
6198                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
6199                             ExtLoad),
6200                 ExtLoad.getValue(1));
6201       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6202     }
6203   }
6204
6205   if (N0.getOpcode() == ISD::SETCC) {
6206     if (!LegalOperations && VT.isVector() &&
6207         N0.getValueType().getVectorElementType() == MVT::i1) {
6208       EVT N0VT = N0.getOperand(0).getValueType();
6209       if (getSetCCResultType(N0VT) == N0.getValueType())
6210         return SDValue();
6211
6212       // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
6213       // Only do this before legalize for now.
6214       EVT EltVT = VT.getVectorElementType();
6215       SDLoc DL(N);
6216       SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
6217                                     DAG.getConstant(1, DL, EltVT));
6218       if (VT.getSizeInBits() == N0VT.getSizeInBits())
6219         // We know that the # elements of the results is the same as the
6220         // # elements of the compare (and the # elements of the compare result
6221         // for that matter).  Check to see that they are the same size.  If so,
6222         // we know that the element size of the sext'd result matches the
6223         // element size of the compare operands.
6224         return DAG.getNode(ISD::AND, DL, VT,
6225                            DAG.getSetCC(DL, VT, N0.getOperand(0),
6226                                          N0.getOperand(1),
6227                                  cast<CondCodeSDNode>(N0.getOperand(2))->get()),
6228                            DAG.getNode(ISD::BUILD_VECTOR, DL, VT,
6229                                        OneOps));
6230
6231       // If the desired elements are smaller or larger than the source
6232       // elements we can use a matching integer vector type and then
6233       // truncate/sign extend
6234       EVT MatchingElementType =
6235         EVT::getIntegerVT(*DAG.getContext(),
6236                           N0VT.getScalarType().getSizeInBits());
6237       EVT MatchingVectorType =
6238         EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
6239                          N0VT.getVectorNumElements());
6240       SDValue VsetCC =
6241         DAG.getSetCC(DL, MatchingVectorType, N0.getOperand(0),
6242                       N0.getOperand(1),
6243                       cast<CondCodeSDNode>(N0.getOperand(2))->get());
6244       return DAG.getNode(ISD::AND, DL, VT,
6245                          DAG.getSExtOrTrunc(VsetCC, DL, VT),
6246                          DAG.getNode(ISD::BUILD_VECTOR, DL, VT, OneOps));
6247     }
6248
6249     // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6250     SDLoc DL(N);
6251     SDValue SCC =
6252       SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6253                        DAG.getConstant(1, DL, VT), DAG.getConstant(0, DL, VT),
6254                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6255     if (SCC.getNode()) return SCC;
6256   }
6257
6258   // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
6259   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
6260       isa<ConstantSDNode>(N0.getOperand(1)) &&
6261       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
6262       N0.hasOneUse()) {
6263     SDValue ShAmt = N0.getOperand(1);
6264     unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
6265     if (N0.getOpcode() == ISD::SHL) {
6266       SDValue InnerZExt = N0.getOperand(0);
6267       // If the original shl may be shifting out bits, do not perform this
6268       // transformation.
6269       unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
6270         InnerZExt.getOperand(0).getValueType().getSizeInBits();
6271       if (ShAmtVal > KnownZeroBits)
6272         return SDValue();
6273     }
6274
6275     SDLoc DL(N);
6276
6277     // Ensure that the shift amount is wide enough for the shifted value.
6278     if (VT.getSizeInBits() >= 256)
6279       ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
6280
6281     return DAG.getNode(N0.getOpcode(), DL, VT,
6282                        DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
6283                        ShAmt);
6284   }
6285
6286   return SDValue();
6287 }
6288
6289 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
6290   SDValue N0 = N->getOperand(0);
6291   EVT VT = N->getValueType(0);
6292
6293   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6294                                               LegalOperations))
6295     return SDValue(Res, 0);
6296
6297   // fold (aext (aext x)) -> (aext x)
6298   // fold (aext (zext x)) -> (zext x)
6299   // fold (aext (sext x)) -> (sext x)
6300   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
6301       N0.getOpcode() == ISD::ZERO_EXTEND ||
6302       N0.getOpcode() == ISD::SIGN_EXTEND)
6303     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
6304
6305   // fold (aext (truncate (load x))) -> (aext (smaller load x))
6306   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
6307   if (N0.getOpcode() == ISD::TRUNCATE) {
6308     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
6309     if (NarrowLoad.getNode()) {
6310       SDNode* oye = N0.getNode()->getOperand(0).getNode();
6311       if (NarrowLoad.getNode() != N0.getNode()) {
6312         CombineTo(N0.getNode(), NarrowLoad);
6313         // CombineTo deleted the truncate, if needed, but not what's under it.
6314         AddToWorklist(oye);
6315       }
6316       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6317     }
6318   }
6319
6320   // fold (aext (truncate x))
6321   if (N0.getOpcode() == ISD::TRUNCATE) {
6322     SDValue TruncOp = N0.getOperand(0);
6323     if (TruncOp.getValueType() == VT)
6324       return TruncOp; // x iff x size == zext size.
6325     if (TruncOp.getValueType().bitsGT(VT))
6326       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
6327     return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
6328   }
6329
6330   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
6331   // if the trunc is not free.
6332   if (N0.getOpcode() == ISD::AND &&
6333       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6334       N0.getOperand(1).getOpcode() == ISD::Constant &&
6335       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6336                           N0.getValueType())) {
6337     SDValue X = N0.getOperand(0).getOperand(0);
6338     if (X.getValueType().bitsLT(VT)) {
6339       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
6340     } else if (X.getValueType().bitsGT(VT)) {
6341       X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
6342     }
6343     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6344     Mask = Mask.zext(VT.getSizeInBits());
6345     SDLoc DL(N);
6346     return DAG.getNode(ISD::AND, DL, VT,
6347                        X, DAG.getConstant(Mask, DL, VT));
6348   }
6349
6350   // fold (aext (load x)) -> (aext (truncate (extload x)))
6351   // None of the supported targets knows how to perform load and any_ext
6352   // on vectors in one instruction.  We only perform this transformation on
6353   // scalars.
6354   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
6355       ISD::isUNINDEXEDLoad(N0.getNode()) &&
6356       TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
6357     bool DoXform = true;
6358     SmallVector<SDNode*, 4> SetCCs;
6359     if (!N0.hasOneUse())
6360       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
6361     if (DoXform) {
6362       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6363       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
6364                                        LN0->getChain(),
6365                                        LN0->getBasePtr(), N0.getValueType(),
6366                                        LN0->getMemOperand());
6367       CombineTo(N, ExtLoad);
6368       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6369                                   N0.getValueType(), ExtLoad);
6370       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6371       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6372                       ISD::ANY_EXTEND);
6373       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6374     }
6375   }
6376
6377   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
6378   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
6379   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
6380   if (N0.getOpcode() == ISD::LOAD &&
6381       !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6382       N0.hasOneUse()) {
6383     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6384     ISD::LoadExtType ExtType = LN0->getExtensionType();
6385     EVT MemVT = LN0->getMemoryVT();
6386     if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) {
6387       SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
6388                                        VT, LN0->getChain(), LN0->getBasePtr(),
6389                                        MemVT, LN0->getMemOperand());
6390       CombineTo(N, ExtLoad);
6391       CombineTo(N0.getNode(),
6392                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6393                             N0.getValueType(), ExtLoad),
6394                 ExtLoad.getValue(1));
6395       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6396     }
6397   }
6398
6399   if (N0.getOpcode() == ISD::SETCC) {
6400     // For vectors:
6401     // aext(setcc) -> vsetcc
6402     // aext(setcc) -> truncate(vsetcc)
6403     // aext(setcc) -> aext(vsetcc)
6404     // Only do this before legalize for now.
6405     if (VT.isVector() && !LegalOperations) {
6406       EVT N0VT = N0.getOperand(0).getValueType();
6407         // We know that the # elements of the results is the same as the
6408         // # elements of the compare (and the # elements of the compare result
6409         // for that matter).  Check to see that they are the same size.  If so,
6410         // we know that the element size of the sext'd result matches the
6411         // element size of the compare operands.
6412       if (VT.getSizeInBits() == N0VT.getSizeInBits())
6413         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6414                              N0.getOperand(1),
6415                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
6416       // If the desired elements are smaller or larger than the source
6417       // elements we can use a matching integer vector type and then
6418       // truncate/any extend
6419       else {
6420         EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6421         SDValue VsetCC =
6422           DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
6423                         N0.getOperand(1),
6424                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
6425         return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
6426       }
6427     }
6428
6429     // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6430     SDLoc DL(N);
6431     SDValue SCC =
6432       SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6433                        DAG.getConstant(1, DL, VT), DAG.getConstant(0, DL, VT),
6434                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6435     if (SCC.getNode())
6436       return SCC;
6437   }
6438
6439   return SDValue();
6440 }
6441
6442 /// See if the specified operand can be simplified with the knowledge that only
6443 /// the bits specified by Mask are used.  If so, return the simpler operand,
6444 /// otherwise return a null SDValue.
6445 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
6446   switch (V.getOpcode()) {
6447   default: break;
6448   case ISD::Constant: {
6449     const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
6450     assert(CV && "Const value should be ConstSDNode.");
6451     const APInt &CVal = CV->getAPIntValue();
6452     APInt NewVal = CVal & Mask;
6453     if (NewVal != CVal)
6454       return DAG.getConstant(NewVal, SDLoc(V), V.getValueType());
6455     break;
6456   }
6457   case ISD::OR:
6458   case ISD::XOR:
6459     // If the LHS or RHS don't contribute bits to the or, drop them.
6460     if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
6461       return V.getOperand(1);
6462     if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
6463       return V.getOperand(0);
6464     break;
6465   case ISD::SRL:
6466     // Only look at single-use SRLs.
6467     if (!V.getNode()->hasOneUse())
6468       break;
6469     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
6470       // See if we can recursively simplify the LHS.
6471       unsigned Amt = RHSC->getZExtValue();
6472
6473       // Watch out for shift count overflow though.
6474       if (Amt >= Mask.getBitWidth()) break;
6475       APInt NewMask = Mask << Amt;
6476       SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
6477       if (SimplifyLHS.getNode())
6478         return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
6479                            SimplifyLHS, V.getOperand(1));
6480     }
6481   }
6482   return SDValue();
6483 }
6484
6485 /// If the result of a wider load is shifted to right of N  bits and then
6486 /// truncated to a narrower type and where N is a multiple of number of bits of
6487 /// the narrower type, transform it to a narrower load from address + N / num of
6488 /// bits of new type. If the result is to be extended, also fold the extension
6489 /// to form a extending load.
6490 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
6491   unsigned Opc = N->getOpcode();
6492
6493   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
6494   SDValue N0 = N->getOperand(0);
6495   EVT VT = N->getValueType(0);
6496   EVT ExtVT = VT;
6497
6498   // This transformation isn't valid for vector loads.
6499   if (VT.isVector())
6500     return SDValue();
6501
6502   // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
6503   // extended to VT.
6504   if (Opc == ISD::SIGN_EXTEND_INREG) {
6505     ExtType = ISD::SEXTLOAD;
6506     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
6507   } else if (Opc == ISD::SRL) {
6508     // Another special-case: SRL is basically zero-extending a narrower value.
6509     ExtType = ISD::ZEXTLOAD;
6510     N0 = SDValue(N, 0);
6511     ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
6512     if (!N01) return SDValue();
6513     ExtVT = EVT::getIntegerVT(*DAG.getContext(),
6514                               VT.getSizeInBits() - N01->getZExtValue());
6515   }
6516   if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT))
6517     return SDValue();
6518
6519   unsigned EVTBits = ExtVT.getSizeInBits();
6520
6521   // Do not generate loads of non-round integer types since these can
6522   // be expensive (and would be wrong if the type is not byte sized).
6523   if (!ExtVT.isRound())
6524     return SDValue();
6525
6526   unsigned ShAmt = 0;
6527   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
6528     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6529       ShAmt = N01->getZExtValue();
6530       // Is the shift amount a multiple of size of VT?
6531       if ((ShAmt & (EVTBits-1)) == 0) {
6532         N0 = N0.getOperand(0);
6533         // Is the load width a multiple of size of VT?
6534         if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
6535           return SDValue();
6536       }
6537
6538       // At this point, we must have a load or else we can't do the transform.
6539       if (!isa<LoadSDNode>(N0)) return SDValue();
6540
6541       // Because a SRL must be assumed to *need* to zero-extend the high bits
6542       // (as opposed to anyext the high bits), we can't combine the zextload
6543       // lowering of SRL and an sextload.
6544       if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
6545         return SDValue();
6546
6547       // If the shift amount is larger than the input type then we're not
6548       // accessing any of the loaded bytes.  If the load was a zextload/extload
6549       // then the result of the shift+trunc is zero/undef (handled elsewhere).
6550       if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
6551         return SDValue();
6552     }
6553   }
6554
6555   // If the load is shifted left (and the result isn't shifted back right),
6556   // we can fold the truncate through the shift.
6557   unsigned ShLeftAmt = 0;
6558   if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
6559       ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
6560     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6561       ShLeftAmt = N01->getZExtValue();
6562       N0 = N0.getOperand(0);
6563     }
6564   }
6565
6566   // If we haven't found a load, we can't narrow it.  Don't transform one with
6567   // multiple uses, this would require adding a new load.
6568   if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
6569     return SDValue();
6570
6571   // Don't change the width of a volatile load.
6572   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6573   if (LN0->isVolatile())
6574     return SDValue();
6575
6576   // Verify that we are actually reducing a load width here.
6577   if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
6578     return SDValue();
6579
6580   // For the transform to be legal, the load must produce only two values
6581   // (the value loaded and the chain).  Don't transform a pre-increment
6582   // load, for example, which produces an extra value.  Otherwise the
6583   // transformation is not equivalent, and the downstream logic to replace
6584   // uses gets things wrong.
6585   if (LN0->getNumValues() > 2)
6586     return SDValue();
6587
6588   // If the load that we're shrinking is an extload and we're not just
6589   // discarding the extension we can't simply shrink the load. Bail.
6590   // TODO: It would be possible to merge the extensions in some cases.
6591   if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
6592       LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
6593     return SDValue();
6594
6595   if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT))
6596     return SDValue();
6597
6598   EVT PtrType = N0.getOperand(1).getValueType();
6599
6600   if (PtrType == MVT::Untyped || PtrType.isExtended())
6601     // It's not possible to generate a constant of extended or untyped type.
6602     return SDValue();
6603
6604   // For big endian targets, we need to adjust the offset to the pointer to
6605   // load the correct bytes.
6606   if (TLI.isBigEndian()) {
6607     unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
6608     unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
6609     ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
6610   }
6611
6612   uint64_t PtrOff = ShAmt / 8;
6613   unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
6614   SDLoc DL(LN0);
6615   SDValue NewPtr = DAG.getNode(ISD::ADD, DL,
6616                                PtrType, LN0->getBasePtr(),
6617                                DAG.getConstant(PtrOff, DL, PtrType));
6618   AddToWorklist(NewPtr.getNode());
6619
6620   SDValue Load;
6621   if (ExtType == ISD::NON_EXTLOAD)
6622     Load =  DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
6623                         LN0->getPointerInfo().getWithOffset(PtrOff),
6624                         LN0->isVolatile(), LN0->isNonTemporal(),
6625                         LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6626   else
6627     Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
6628                           LN0->getPointerInfo().getWithOffset(PtrOff),
6629                           ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
6630                           LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6631
6632   // Replace the old load's chain with the new load's chain.
6633   WorklistRemover DeadNodes(*this);
6634   DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6635
6636   // Shift the result left, if we've swallowed a left shift.
6637   SDValue Result = Load;
6638   if (ShLeftAmt != 0) {
6639     EVT ShImmTy = getShiftAmountTy(Result.getValueType());
6640     if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
6641       ShImmTy = VT;
6642     // If the shift amount is as large as the result size (but, presumably,
6643     // no larger than the source) then the useful bits of the result are
6644     // zero; we can't simply return the shortened shift, because the result
6645     // of that operation is undefined.
6646     SDLoc DL(N0);
6647     if (ShLeftAmt >= VT.getSizeInBits())
6648       Result = DAG.getConstant(0, DL, VT);
6649     else
6650       Result = DAG.getNode(ISD::SHL, DL, VT,
6651                           Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy));
6652   }
6653
6654   // Return the new loaded value.
6655   return Result;
6656 }
6657
6658 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
6659   SDValue N0 = N->getOperand(0);
6660   SDValue N1 = N->getOperand(1);
6661   EVT VT = N->getValueType(0);
6662   EVT EVT = cast<VTSDNode>(N1)->getVT();
6663   unsigned VTBits = VT.getScalarType().getSizeInBits();
6664   unsigned EVTBits = EVT.getScalarType().getSizeInBits();
6665
6666   // fold (sext_in_reg c1) -> c1
6667   if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
6668     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
6669
6670   // If the input is already sign extended, just drop the extension.
6671   if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
6672     return N0;
6673
6674   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
6675   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
6676       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
6677     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6678                        N0.getOperand(0), N1);
6679
6680   // fold (sext_in_reg (sext x)) -> (sext x)
6681   // fold (sext_in_reg (aext x)) -> (sext x)
6682   // if x is small enough.
6683   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
6684     SDValue N00 = N0.getOperand(0);
6685     if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
6686         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
6687       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
6688   }
6689
6690   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
6691   if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
6692     return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
6693
6694   // fold operands of sext_in_reg based on knowledge that the top bits are not
6695   // demanded.
6696   if (SimplifyDemandedBits(SDValue(N, 0)))
6697     return SDValue(N, 0);
6698
6699   // fold (sext_in_reg (load x)) -> (smaller sextload x)
6700   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
6701   SDValue NarrowLoad = ReduceLoadWidth(N);
6702   if (NarrowLoad.getNode())
6703     return NarrowLoad;
6704
6705   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
6706   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
6707   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
6708   if (N0.getOpcode() == ISD::SRL) {
6709     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
6710       if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
6711         // We can turn this into an SRA iff the input to the SRL is already sign
6712         // extended enough.
6713         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
6714         if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
6715           return DAG.getNode(ISD::SRA, SDLoc(N), VT,
6716                              N0.getOperand(0), N0.getOperand(1));
6717       }
6718   }
6719
6720   // fold (sext_inreg (extload x)) -> (sextload x)
6721   if (ISD::isEXTLoad(N0.getNode()) &&
6722       ISD::isUNINDEXEDLoad(N0.getNode()) &&
6723       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6724       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6725        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6726     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6727     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6728                                      LN0->getChain(),
6729                                      LN0->getBasePtr(), EVT,
6730                                      LN0->getMemOperand());
6731     CombineTo(N, ExtLoad);
6732     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6733     AddToWorklist(ExtLoad.getNode());
6734     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6735   }
6736   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
6737   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6738       N0.hasOneUse() &&
6739       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6740       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6741        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6742     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6743     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6744                                      LN0->getChain(),
6745                                      LN0->getBasePtr(), EVT,
6746                                      LN0->getMemOperand());
6747     CombineTo(N, ExtLoad);
6748     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6749     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6750   }
6751
6752   // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
6753   if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
6754     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
6755                                        N0.getOperand(1), false);
6756     if (BSwap.getNode())
6757       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6758                          BSwap, N1);
6759   }
6760
6761   // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
6762   // into a build_vector.
6763   if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
6764     SmallVector<SDValue, 8> Elts;
6765     unsigned NumElts = N0->getNumOperands();
6766     unsigned ShAmt = VTBits - EVTBits;
6767
6768     for (unsigned i = 0; i != NumElts; ++i) {
6769       SDValue Op = N0->getOperand(i);
6770       if (Op->getOpcode() == ISD::UNDEF) {
6771         Elts.push_back(Op);
6772         continue;
6773       }
6774
6775       ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
6776       const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
6777       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
6778                                      SDLoc(Op), Op.getValueType()));
6779     }
6780
6781     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts);
6782   }
6783
6784   return SDValue();
6785 }
6786
6787 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
6788   SDValue N0 = N->getOperand(0);
6789   EVT VT = N->getValueType(0);
6790   bool isLE = TLI.isLittleEndian();
6791
6792   // noop truncate
6793   if (N0.getValueType() == N->getValueType(0))
6794     return N0;
6795   // fold (truncate c1) -> c1
6796   if (isConstantIntBuildVectorOrConstantInt(N0))
6797     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
6798   // fold (truncate (truncate x)) -> (truncate x)
6799   if (N0.getOpcode() == ISD::TRUNCATE)
6800     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6801   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
6802   if (N0.getOpcode() == ISD::ZERO_EXTEND ||
6803       N0.getOpcode() == ISD::SIGN_EXTEND ||
6804       N0.getOpcode() == ISD::ANY_EXTEND) {
6805     if (N0.getOperand(0).getValueType().bitsLT(VT))
6806       // if the source is smaller than the dest, we still need an extend
6807       return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
6808                          N0.getOperand(0));
6809     if (N0.getOperand(0).getValueType().bitsGT(VT))
6810       // if the source is larger than the dest, than we just need the truncate
6811       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6812     // if the source and dest are the same type, we can drop both the extend
6813     // and the truncate.
6814     return N0.getOperand(0);
6815   }
6816
6817   // Fold extract-and-trunc into a narrow extract. For example:
6818   //   i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
6819   //   i32 y = TRUNCATE(i64 x)
6820   //        -- becomes --
6821   //   v16i8 b = BITCAST (v2i64 val)
6822   //   i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
6823   //
6824   // Note: We only run this optimization after type legalization (which often
6825   // creates this pattern) and before operation legalization after which
6826   // we need to be more careful about the vector instructions that we generate.
6827   if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6828       LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
6829
6830     EVT VecTy = N0.getOperand(0).getValueType();
6831     EVT ExTy = N0.getValueType();
6832     EVT TrTy = N->getValueType(0);
6833
6834     unsigned NumElem = VecTy.getVectorNumElements();
6835     unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
6836
6837     EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
6838     assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
6839
6840     SDValue EltNo = N0->getOperand(1);
6841     if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
6842       int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6843       EVT IndexTy = TLI.getVectorIdxTy();
6844       int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
6845
6846       SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
6847                               NVT, N0.getOperand(0));
6848
6849       SDLoc DL(N);
6850       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
6851                          DL, TrTy, V,
6852                          DAG.getConstant(Index, DL, IndexTy));
6853     }
6854   }
6855
6856   // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
6857   if (N0.getOpcode() == ISD::SELECT) {
6858     EVT SrcVT = N0.getValueType();
6859     if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
6860         TLI.isTruncateFree(SrcVT, VT)) {
6861       SDLoc SL(N0);
6862       SDValue Cond = N0.getOperand(0);
6863       SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
6864       SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
6865       return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
6866     }
6867   }
6868
6869   // Fold a series of buildvector, bitcast, and truncate if possible.
6870   // For example fold
6871   //   (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
6872   //   (2xi32 (buildvector x, y)).
6873   if (Level == AfterLegalizeVectorOps && VT.isVector() &&
6874       N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
6875       N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
6876       N0.getOperand(0).hasOneUse()) {
6877
6878     SDValue BuildVect = N0.getOperand(0);
6879     EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
6880     EVT TruncVecEltTy = VT.getVectorElementType();
6881
6882     // Check that the element types match.
6883     if (BuildVectEltTy == TruncVecEltTy) {
6884       // Now we only need to compute the offset of the truncated elements.
6885       unsigned BuildVecNumElts =  BuildVect.getNumOperands();
6886       unsigned TruncVecNumElts = VT.getVectorNumElements();
6887       unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
6888
6889       assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
6890              "Invalid number of elements");
6891
6892       SmallVector<SDValue, 8> Opnds;
6893       for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
6894         Opnds.push_back(BuildVect.getOperand(i));
6895
6896       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
6897     }
6898   }
6899
6900   // See if we can simplify the input to this truncate through knowledge that
6901   // only the low bits are being used.
6902   // For example "trunc (or (shl x, 8), y)" // -> trunc y
6903   // Currently we only perform this optimization on scalars because vectors
6904   // may have different active low bits.
6905   if (!VT.isVector()) {
6906     SDValue Shorter =
6907       GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
6908                                                VT.getSizeInBits()));
6909     if (Shorter.getNode())
6910       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
6911   }
6912   // fold (truncate (load x)) -> (smaller load x)
6913   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
6914   if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
6915     SDValue Reduced = ReduceLoadWidth(N);
6916     if (Reduced.getNode())
6917       return Reduced;
6918     // Handle the case where the load remains an extending load even
6919     // after truncation.
6920     if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
6921       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6922       if (!LN0->isVolatile() &&
6923           LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
6924         SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
6925                                          VT, LN0->getChain(), LN0->getBasePtr(),
6926                                          LN0->getMemoryVT(),
6927                                          LN0->getMemOperand());
6928         DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
6929         return NewLoad;
6930       }
6931     }
6932   }
6933   // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
6934   // where ... are all 'undef'.
6935   if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
6936     SmallVector<EVT, 8> VTs;
6937     SDValue V;
6938     unsigned Idx = 0;
6939     unsigned NumDefs = 0;
6940
6941     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
6942       SDValue X = N0.getOperand(i);
6943       if (X.getOpcode() != ISD::UNDEF) {
6944         V = X;
6945         Idx = i;
6946         NumDefs++;
6947       }
6948       // Stop if more than one members are non-undef.
6949       if (NumDefs > 1)
6950         break;
6951       VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
6952                                      VT.getVectorElementType(),
6953                                      X.getValueType().getVectorNumElements()));
6954     }
6955
6956     if (NumDefs == 0)
6957       return DAG.getUNDEF(VT);
6958
6959     if (NumDefs == 1) {
6960       assert(V.getNode() && "The single defined operand is empty!");
6961       SmallVector<SDValue, 8> Opnds;
6962       for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
6963         if (i != Idx) {
6964           Opnds.push_back(DAG.getUNDEF(VTs[i]));
6965           continue;
6966         }
6967         SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
6968         AddToWorklist(NV.getNode());
6969         Opnds.push_back(NV);
6970       }
6971       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
6972     }
6973   }
6974
6975   // Simplify the operands using demanded-bits information.
6976   if (!VT.isVector() &&
6977       SimplifyDemandedBits(SDValue(N, 0)))
6978     return SDValue(N, 0);
6979
6980   return SDValue();
6981 }
6982
6983 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
6984   SDValue Elt = N->getOperand(i);
6985   if (Elt.getOpcode() != ISD::MERGE_VALUES)
6986     return Elt.getNode();
6987   return Elt.getOperand(Elt.getResNo()).getNode();
6988 }
6989
6990 /// build_pair (load, load) -> load
6991 /// if load locations are consecutive.
6992 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
6993   assert(N->getOpcode() == ISD::BUILD_PAIR);
6994
6995   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
6996   LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
6997   if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
6998       LD1->getAddressSpace() != LD2->getAddressSpace())
6999     return SDValue();
7000   EVT LD1VT = LD1->getValueType(0);
7001
7002   if (ISD::isNON_EXTLoad(LD2) &&
7003       LD2->hasOneUse() &&
7004       // If both are volatile this would reduce the number of volatile loads.
7005       // If one is volatile it might be ok, but play conservative and bail out.
7006       !LD1->isVolatile() &&
7007       !LD2->isVolatile() &&
7008       DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
7009     unsigned Align = LD1->getAlignment();
7010     unsigned NewAlign = TLI.getDataLayout()->
7011       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
7012
7013     if (NewAlign <= Align &&
7014         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
7015       return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
7016                          LD1->getBasePtr(), LD1->getPointerInfo(),
7017                          false, false, false, Align);
7018   }
7019
7020   return SDValue();
7021 }
7022
7023 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
7024   SDValue N0 = N->getOperand(0);
7025   EVT VT = N->getValueType(0);
7026
7027   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
7028   // Only do this before legalize, since afterward the target may be depending
7029   // on the bitconvert.
7030   // First check to see if this is all constant.
7031   if (!LegalTypes &&
7032       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
7033       VT.isVector()) {
7034     bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
7035
7036     EVT DestEltVT = N->getValueType(0).getVectorElementType();
7037     assert(!DestEltVT.isVector() &&
7038            "Element type of vector ValueType must not be vector!");
7039     if (isSimple)
7040       return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
7041   }
7042
7043   // If the input is a constant, let getNode fold it.
7044   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
7045     // If we can't allow illegal operations, we need to check that this is just
7046     // a fp -> int or int -> conversion and that the resulting operation will
7047     // be legal.
7048     if (!LegalOperations ||
7049         (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() &&
7050          TLI.isOperationLegal(ISD::ConstantFP, VT)) ||
7051         (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() &&
7052          TLI.isOperationLegal(ISD::Constant, VT)))
7053       return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
7054   }
7055
7056   // (conv (conv x, t1), t2) -> (conv x, t2)
7057   if (N0.getOpcode() == ISD::BITCAST)
7058     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
7059                        N0.getOperand(0));
7060
7061   // fold (conv (load x)) -> (load (conv*)x)
7062   // If the resultant load doesn't need a higher alignment than the original!
7063   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7064       // Do not change the width of a volatile load.
7065       !cast<LoadSDNode>(N0)->isVolatile() &&
7066       // Do not remove the cast if the types differ in endian layout.
7067       TLI.hasBigEndianPartOrdering(N0.getValueType()) ==
7068       TLI.hasBigEndianPartOrdering(VT) &&
7069       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
7070       TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
7071     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7072     unsigned Align = TLI.getDataLayout()->
7073       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
7074     unsigned OrigAlign = LN0->getAlignment();
7075
7076     if (Align <= OrigAlign) {
7077       SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
7078                                  LN0->getBasePtr(), LN0->getPointerInfo(),
7079                                  LN0->isVolatile(), LN0->isNonTemporal(),
7080                                  LN0->isInvariant(), OrigAlign,
7081                                  LN0->getAAInfo());
7082       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
7083       return Load;
7084     }
7085   }
7086
7087   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
7088   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
7089   // This often reduces constant pool loads.
7090   if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
7091        (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
7092       N0.getNode()->hasOneUse() && VT.isInteger() &&
7093       !VT.isVector() && !N0.getValueType().isVector()) {
7094     SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
7095                                   N0.getOperand(0));
7096     AddToWorklist(NewConv.getNode());
7097
7098     SDLoc DL(N);
7099     APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7100     if (N0.getOpcode() == ISD::FNEG)
7101       return DAG.getNode(ISD::XOR, DL, VT,
7102                          NewConv, DAG.getConstant(SignBit, DL, VT));
7103     assert(N0.getOpcode() == ISD::FABS);
7104     return DAG.getNode(ISD::AND, DL, VT,
7105                        NewConv, DAG.getConstant(~SignBit, DL, VT));
7106   }
7107
7108   // fold (bitconvert (fcopysign cst, x)) ->
7109   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
7110   // Note that we don't handle (copysign x, cst) because this can always be
7111   // folded to an fneg or fabs.
7112   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
7113       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
7114       VT.isInteger() && !VT.isVector()) {
7115     unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
7116     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
7117     if (isTypeLegal(IntXVT)) {
7118       SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
7119                               IntXVT, N0.getOperand(1));
7120       AddToWorklist(X.getNode());
7121
7122       // If X has a different width than the result/lhs, sext it or truncate it.
7123       unsigned VTWidth = VT.getSizeInBits();
7124       if (OrigXWidth < VTWidth) {
7125         X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
7126         AddToWorklist(X.getNode());
7127       } else if (OrigXWidth > VTWidth) {
7128         // To get the sign bit in the right place, we have to shift it right
7129         // before truncating.
7130         SDLoc DL(X);
7131         X = DAG.getNode(ISD::SRL, DL,
7132                         X.getValueType(), X,
7133                         DAG.getConstant(OrigXWidth-VTWidth, DL,
7134                                         X.getValueType()));
7135         AddToWorklist(X.getNode());
7136         X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
7137         AddToWorklist(X.getNode());
7138       }
7139
7140       APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7141       X = DAG.getNode(ISD::AND, SDLoc(X), VT,
7142                       X, DAG.getConstant(SignBit, SDLoc(X), VT));
7143       AddToWorklist(X.getNode());
7144
7145       SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
7146                                 VT, N0.getOperand(0));
7147       Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
7148                         Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT));
7149       AddToWorklist(Cst.getNode());
7150
7151       return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
7152     }
7153   }
7154
7155   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
7156   if (N0.getOpcode() == ISD::BUILD_PAIR) {
7157     SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
7158     if (CombineLD.getNode())
7159       return CombineLD;
7160   }
7161
7162   // Remove double bitcasts from shuffles - this is often a legacy of
7163   // XformToShuffleWithZero being used to combine bitmaskings (of
7164   // float vectors bitcast to integer vectors) into shuffles.
7165   // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1)
7166   if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() &&
7167       N0->getOpcode() == ISD::VECTOR_SHUFFLE &&
7168       VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() &&
7169       !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) {
7170     ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0);
7171
7172     // If operands are a bitcast, peek through if it casts the original VT.
7173     // If operands are a UNDEF or constant, just bitcast back to original VT.
7174     auto PeekThroughBitcast = [&](SDValue Op) {
7175       if (Op.getOpcode() == ISD::BITCAST &&
7176           Op.getOperand(0)->getValueType(0) == VT)
7177         return SDValue(Op.getOperand(0));
7178       if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) ||
7179           ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode()))
7180         return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
7181       return SDValue();
7182     };
7183
7184     SDValue SV0 = PeekThroughBitcast(N0->getOperand(0));
7185     SDValue SV1 = PeekThroughBitcast(N0->getOperand(1));
7186     if (!(SV0 && SV1))
7187       return SDValue();
7188
7189     int MaskScale =
7190         VT.getVectorNumElements() / N0.getValueType().getVectorNumElements();
7191     SmallVector<int, 8> NewMask;
7192     for (int M : SVN->getMask())
7193       for (int i = 0; i != MaskScale; ++i)
7194         NewMask.push_back(M < 0 ? -1 : M * MaskScale + i);
7195
7196     bool LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7197     if (!LegalMask) {
7198       std::swap(SV0, SV1);
7199       ShuffleVectorSDNode::commuteMask(NewMask);
7200       LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7201     }
7202
7203     if (LegalMask)
7204       return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask);
7205   }
7206
7207   return SDValue();
7208 }
7209
7210 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
7211   EVT VT = N->getValueType(0);
7212   return CombineConsecutiveLoads(N, VT);
7213 }
7214
7215 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
7216 /// operands. DstEltVT indicates the destination element value type.
7217 SDValue DAGCombiner::
7218 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
7219   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
7220
7221   // If this is already the right type, we're done.
7222   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
7223
7224   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
7225   unsigned DstBitSize = DstEltVT.getSizeInBits();
7226
7227   // If this is a conversion of N elements of one type to N elements of another
7228   // type, convert each element.  This handles FP<->INT cases.
7229   if (SrcBitSize == DstBitSize) {
7230     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7231                               BV->getValueType(0).getVectorNumElements());
7232
7233     // Due to the FP element handling below calling this routine recursively,
7234     // we can end up with a scalar-to-vector node here.
7235     if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
7236       return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
7237                          DAG.getNode(ISD::BITCAST, SDLoc(BV),
7238                                      DstEltVT, BV->getOperand(0)));
7239
7240     SmallVector<SDValue, 8> Ops;
7241     for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
7242       SDValue Op = BV->getOperand(i);
7243       // If the vector element type is not legal, the BUILD_VECTOR operands
7244       // are promoted and implicitly truncated.  Make that explicit here.
7245       if (Op.getValueType() != SrcEltVT)
7246         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
7247       Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
7248                                 DstEltVT, Op));
7249       AddToWorklist(Ops.back().getNode());
7250     }
7251     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
7252   }
7253
7254   // Otherwise, we're growing or shrinking the elements.  To avoid having to
7255   // handle annoying details of growing/shrinking FP values, we convert them to
7256   // int first.
7257   if (SrcEltVT.isFloatingPoint()) {
7258     // Convert the input float vector to a int vector where the elements are the
7259     // same sizes.
7260     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
7261     BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
7262     SrcEltVT = IntVT;
7263   }
7264
7265   // Now we know the input is an integer vector.  If the output is a FP type,
7266   // convert to integer first, then to FP of the right size.
7267   if (DstEltVT.isFloatingPoint()) {
7268     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
7269     SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
7270
7271     // Next, convert to FP elements of the same size.
7272     return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
7273   }
7274
7275   SDLoc DL(BV);
7276
7277   // Okay, we know the src/dst types are both integers of differing types.
7278   // Handling growing first.
7279   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
7280   if (SrcBitSize < DstBitSize) {
7281     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
7282
7283     SmallVector<SDValue, 8> Ops;
7284     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
7285          i += NumInputsPerOutput) {
7286       bool isLE = TLI.isLittleEndian();
7287       APInt NewBits = APInt(DstBitSize, 0);
7288       bool EltIsUndef = true;
7289       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
7290         // Shift the previously computed bits over.
7291         NewBits <<= SrcBitSize;
7292         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
7293         if (Op.getOpcode() == ISD::UNDEF) continue;
7294         EltIsUndef = false;
7295
7296         NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
7297                    zextOrTrunc(SrcBitSize).zext(DstBitSize);
7298       }
7299
7300       if (EltIsUndef)
7301         Ops.push_back(DAG.getUNDEF(DstEltVT));
7302       else
7303         Ops.push_back(DAG.getConstant(NewBits, DL, DstEltVT));
7304     }
7305
7306     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
7307     return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
7308   }
7309
7310   // Finally, this must be the case where we are shrinking elements: each input
7311   // turns into multiple outputs.
7312   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
7313   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7314                             NumOutputsPerInput*BV->getNumOperands());
7315   SmallVector<SDValue, 8> Ops;
7316
7317   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
7318     if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
7319       Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT));
7320       continue;
7321     }
7322
7323     APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
7324                   getAPIntValue().zextOrTrunc(SrcBitSize);
7325
7326     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
7327       APInt ThisVal = OpVal.trunc(DstBitSize);
7328       Ops.push_back(DAG.getConstant(ThisVal, DL, DstEltVT));
7329       OpVal = OpVal.lshr(DstBitSize);
7330     }
7331
7332     // For big endian targets, swap the order of the pieces of each element.
7333     if (TLI.isBigEndian())
7334       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
7335   }
7336
7337   return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
7338 }
7339
7340 /// Try to perform FMA combining on a given FADD node.
7341 SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) {
7342   SDValue N0 = N->getOperand(0);
7343   SDValue N1 = N->getOperand(1);
7344   EVT VT = N->getValueType(0);
7345   SDLoc SL(N);
7346
7347   const TargetOptions &Options = DAG.getTarget().Options;
7348   bool UnsafeFPMath = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
7349                        Options.UnsafeFPMath);
7350
7351   // Floating-point multiply-add with intermediate rounding.
7352   bool HasFMAD = (LegalOperations &&
7353                   TLI.isOperationLegal(ISD::FMAD, VT));
7354
7355   // Floating-point multiply-add without intermediate rounding.
7356   bool HasFMA = ((!LegalOperations ||
7357                   TLI.isOperationLegalOrCustom(ISD::FMA, VT)) &&
7358                  TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7359                  UnsafeFPMath);
7360
7361   // No valid opcode, do not combine.
7362   if (!HasFMAD && !HasFMA)
7363     return SDValue();
7364
7365   // Always prefer FMAD to FMA for precision.
7366   unsigned int PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7367   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7368   bool LookThroughFPExt = TLI.isFPExtFree(VT);
7369
7370   // fold (fadd (fmul x, y), z) -> (fma x, y, z)
7371   if (N0.getOpcode() == ISD::FMUL &&
7372       (Aggressive || N0->hasOneUse())) {
7373     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7374                        N0.getOperand(0), N0.getOperand(1), N1);
7375   }
7376
7377   // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
7378   // Note: Commutes FADD operands.
7379   if (N1.getOpcode() == ISD::FMUL &&
7380       (Aggressive || N1->hasOneUse())) {
7381     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7382                        N1.getOperand(0), N1.getOperand(1), N0);
7383   }
7384
7385   // Look through FP_EXTEND nodes to do more combining.
7386   if (UnsafeFPMath && LookThroughFPExt) {
7387     // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
7388     if (N0.getOpcode() == ISD::FP_EXTEND) {
7389       SDValue N00 = N0.getOperand(0);
7390       if (N00.getOpcode() == ISD::FMUL)
7391         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7392                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7393                                        N00.getOperand(0)),
7394                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7395                                        N00.getOperand(1)), N1);
7396     }
7397
7398     // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x)
7399     // Note: Commutes FADD operands.
7400     if (N1.getOpcode() == ISD::FP_EXTEND) {
7401       SDValue N10 = N1.getOperand(0);
7402       if (N10.getOpcode() == ISD::FMUL)
7403         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7404                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7405                                        N10.getOperand(0)),
7406                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7407                                        N10.getOperand(1)), N0);
7408     }
7409   }
7410
7411   // More folding opportunities when target permits.
7412   if ((UnsafeFPMath || HasFMAD)  && Aggressive) {
7413     // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z))
7414     if (N0.getOpcode() == PreferredFusedOpcode &&
7415         N0.getOperand(2).getOpcode() == ISD::FMUL) {
7416       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7417                          N0.getOperand(0), N0.getOperand(1),
7418                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7419                                      N0.getOperand(2).getOperand(0),
7420                                      N0.getOperand(2).getOperand(1),
7421                                      N1));
7422     }
7423
7424     // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x))
7425     if (N1->getOpcode() == PreferredFusedOpcode &&
7426         N1.getOperand(2).getOpcode() == ISD::FMUL) {
7427       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7428                          N1.getOperand(0), N1.getOperand(1),
7429                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7430                                      N1.getOperand(2).getOperand(0),
7431                                      N1.getOperand(2).getOperand(1),
7432                                      N0));
7433     }
7434
7435     if (UnsafeFPMath && LookThroughFPExt) {
7436       // fold (fadd (fma x, y, (fpext (fmul u, v))), z)
7437       //   -> (fma x, y, (fma (fpext u), (fpext v), z))
7438       auto FoldFAddFMAFPExtFMul = [&] (
7439           SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7440         return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y,
7441                            DAG.getNode(PreferredFusedOpcode, SL, VT,
7442                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7443                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7444                                        Z));
7445       };
7446       if (N0.getOpcode() == PreferredFusedOpcode) {
7447         SDValue N02 = N0.getOperand(2);
7448         if (N02.getOpcode() == ISD::FP_EXTEND) {
7449           SDValue N020 = N02.getOperand(0);
7450           if (N020.getOpcode() == ISD::FMUL)
7451             return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1),
7452                                         N020.getOperand(0), N020.getOperand(1),
7453                                         N1);
7454         }
7455       }
7456
7457       // fold (fadd (fpext (fma x, y, (fmul u, v))), z)
7458       //   -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z))
7459       // FIXME: This turns two single-precision and one double-precision
7460       // operation into two double-precision operations, which might not be
7461       // interesting for all targets, especially GPUs.
7462       auto FoldFAddFPExtFMAFMul = [&] (
7463           SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7464         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7465                            DAG.getNode(ISD::FP_EXTEND, SL, VT, X),
7466                            DAG.getNode(ISD::FP_EXTEND, SL, VT, Y),
7467                            DAG.getNode(PreferredFusedOpcode, SL, VT,
7468                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7469                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7470                                        Z));
7471       };
7472       if (N0.getOpcode() == ISD::FP_EXTEND) {
7473         SDValue N00 = N0.getOperand(0);
7474         if (N00.getOpcode() == PreferredFusedOpcode) {
7475           SDValue N002 = N00.getOperand(2);
7476           if (N002.getOpcode() == ISD::FMUL)
7477             return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1),
7478                                         N002.getOperand(0), N002.getOperand(1),
7479                                         N1);
7480         }
7481       }
7482
7483       // fold (fadd x, (fma y, z, (fpext (fmul u, v)))
7484       //   -> (fma y, z, (fma (fpext u), (fpext v), x))
7485       if (N1.getOpcode() == PreferredFusedOpcode) {
7486         SDValue N12 = N1.getOperand(2);
7487         if (N12.getOpcode() == ISD::FP_EXTEND) {
7488           SDValue N120 = N12.getOperand(0);
7489           if (N120.getOpcode() == ISD::FMUL)
7490             return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1),
7491                                         N120.getOperand(0), N120.getOperand(1),
7492                                         N0);
7493         }
7494       }
7495
7496       // fold (fadd x, (fpext (fma y, z, (fmul u, v)))
7497       //   -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x))
7498       // FIXME: This turns two single-precision and one double-precision
7499       // operation into two double-precision operations, which might not be
7500       // interesting for all targets, especially GPUs.
7501       if (N1.getOpcode() == ISD::FP_EXTEND) {
7502         SDValue N10 = N1.getOperand(0);
7503         if (N10.getOpcode() == PreferredFusedOpcode) {
7504           SDValue N102 = N10.getOperand(2);
7505           if (N102.getOpcode() == ISD::FMUL)
7506             return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1),
7507                                         N102.getOperand(0), N102.getOperand(1),
7508                                         N0);
7509         }
7510       }
7511     }
7512   }
7513
7514   return SDValue();
7515 }
7516
7517 /// Try to perform FMA combining on a given FSUB node.
7518 SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) {
7519   SDValue N0 = N->getOperand(0);
7520   SDValue N1 = N->getOperand(1);
7521   EVT VT = N->getValueType(0);
7522   SDLoc SL(N);
7523
7524   const TargetOptions &Options = DAG.getTarget().Options;
7525   bool UnsafeFPMath = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
7526                        Options.UnsafeFPMath);
7527
7528   // Floating-point multiply-add with intermediate rounding.
7529   bool HasFMAD = (LegalOperations &&
7530                   TLI.isOperationLegal(ISD::FMAD, VT));
7531
7532   // Floating-point multiply-add without intermediate rounding.
7533   bool HasFMA = ((!LegalOperations ||
7534                   TLI.isOperationLegalOrCustom(ISD::FMA, VT)) &&
7535                  TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7536                  UnsafeFPMath);
7537
7538   // No valid opcode, do not combine.
7539   if (!HasFMAD && !HasFMA)
7540     return SDValue();
7541
7542   // Always prefer FMAD to FMA for precision.
7543   unsigned int PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7544   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7545   bool LookThroughFPExt = TLI.isFPExtFree(VT);
7546
7547   // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
7548   if (N0.getOpcode() == ISD::FMUL &&
7549       (Aggressive || N0->hasOneUse())) {
7550     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7551                        N0.getOperand(0), N0.getOperand(1),
7552                        DAG.getNode(ISD::FNEG, SL, VT, N1));
7553   }
7554
7555   // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
7556   // Note: Commutes FSUB operands.
7557   if (N1.getOpcode() == ISD::FMUL &&
7558       (Aggressive || N1->hasOneUse()))
7559     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7560                        DAG.getNode(ISD::FNEG, SL, VT,
7561                                    N1.getOperand(0)),
7562                        N1.getOperand(1), N0);
7563
7564   // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
7565   if (N0.getOpcode() == ISD::FNEG &&
7566       N0.getOperand(0).getOpcode() == ISD::FMUL &&
7567       (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) {
7568     SDValue N00 = N0.getOperand(0).getOperand(0);
7569     SDValue N01 = N0.getOperand(0).getOperand(1);
7570     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7571                        DAG.getNode(ISD::FNEG, SL, VT, N00), N01,
7572                        DAG.getNode(ISD::FNEG, SL, VT, N1));
7573   }
7574
7575   // Look through FP_EXTEND nodes to do more combining.
7576   if (UnsafeFPMath && LookThroughFPExt) {
7577     // fold (fsub (fpext (fmul x, y)), z)
7578     //   -> (fma (fpext x), (fpext y), (fneg z))
7579     if (N0.getOpcode() == ISD::FP_EXTEND) {
7580       SDValue N00 = N0.getOperand(0);
7581       if (N00.getOpcode() == ISD::FMUL)
7582         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7583                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7584                                        N00.getOperand(0)),
7585                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7586                                        N00.getOperand(1)),
7587                            DAG.getNode(ISD::FNEG, SL, VT, N1));
7588     }
7589
7590     // fold (fsub x, (fpext (fmul y, z)))
7591     //   -> (fma (fneg (fpext y)), (fpext z), x)
7592     // Note: Commutes FSUB operands.
7593     if (N1.getOpcode() == ISD::FP_EXTEND) {
7594       SDValue N10 = N1.getOperand(0);
7595       if (N10.getOpcode() == ISD::FMUL)
7596         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7597                            DAG.getNode(ISD::FNEG, SL, VT,
7598                                        DAG.getNode(ISD::FP_EXTEND, SL, VT,
7599                                                    N10.getOperand(0))),
7600                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7601                                        N10.getOperand(1)),
7602                            N0);
7603     }
7604
7605     // fold (fsub (fpext (fneg (fmul, x, y))), z)
7606     //   -> (fneg (fma (fpext x), (fpext y), z))
7607     // Note: This could be removed with appropriate canonicalization of the
7608     // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
7609     // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
7610     // from implementing the canonicalization in visitFSUB.
7611     if (N0.getOpcode() == ISD::FP_EXTEND) {
7612       SDValue N00 = N0.getOperand(0);
7613       if (N00.getOpcode() == ISD::FNEG) {
7614         SDValue N000 = N00.getOperand(0);
7615         if (N000.getOpcode() == ISD::FMUL) {
7616           return DAG.getNode(ISD::FNEG, SL, VT,
7617                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7618                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7619                                                      N000.getOperand(0)),
7620                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7621                                                      N000.getOperand(1)),
7622                                          N1));
7623         }
7624       }
7625     }
7626
7627     // fold (fsub (fneg (fpext (fmul, x, y))), z)
7628     //   -> (fneg (fma (fpext x)), (fpext y), z)
7629     // Note: This could be removed with appropriate canonicalization of the
7630     // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
7631     // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
7632     // from implementing the canonicalization in visitFSUB.
7633     if (N0.getOpcode() == ISD::FNEG) {
7634       SDValue N00 = N0.getOperand(0);
7635       if (N00.getOpcode() == ISD::FP_EXTEND) {
7636         SDValue N000 = N00.getOperand(0);
7637         if (N000.getOpcode() == ISD::FMUL) {
7638           return DAG.getNode(ISD::FNEG, SL, VT,
7639                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7640                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7641                                                      N000.getOperand(0)),
7642                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7643                                                      N000.getOperand(1)),
7644                                          N1));
7645         }
7646       }
7647     }
7648
7649   }
7650
7651   // More folding opportunities when target permits.
7652   if ((UnsafeFPMath || HasFMAD) && Aggressive) {
7653     // fold (fsub (fma x, y, (fmul u, v)), z)
7654     //   -> (fma x, y (fma u, v, (fneg z)))
7655     if (N0.getOpcode() == PreferredFusedOpcode &&
7656         N0.getOperand(2).getOpcode() == ISD::FMUL) {
7657       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7658                          N0.getOperand(0), N0.getOperand(1),
7659                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7660                                      N0.getOperand(2).getOperand(0),
7661                                      N0.getOperand(2).getOperand(1),
7662                                      DAG.getNode(ISD::FNEG, SL, VT,
7663                                                  N1)));
7664     }
7665
7666     // fold (fsub x, (fma y, z, (fmul u, v)))
7667     //   -> (fma (fneg y), z, (fma (fneg u), v, x))
7668     if (N1.getOpcode() == PreferredFusedOpcode &&
7669         N1.getOperand(2).getOpcode() == ISD::FMUL) {
7670       SDValue N20 = N1.getOperand(2).getOperand(0);
7671       SDValue N21 = N1.getOperand(2).getOperand(1);
7672       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7673                          DAG.getNode(ISD::FNEG, SL, VT,
7674                                      N1.getOperand(0)),
7675                          N1.getOperand(1),
7676                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7677                                      DAG.getNode(ISD::FNEG, SL, VT, N20),
7678
7679                                      N21, N0));
7680     }
7681
7682     if (UnsafeFPMath && LookThroughFPExt) {
7683       // fold (fsub (fma x, y, (fpext (fmul u, v))), z)
7684       //   -> (fma x, y (fma (fpext u), (fpext v), (fneg z)))
7685       if (N0.getOpcode() == PreferredFusedOpcode) {
7686         SDValue N02 = N0.getOperand(2);
7687         if (N02.getOpcode() == ISD::FP_EXTEND) {
7688           SDValue N020 = N02.getOperand(0);
7689           if (N020.getOpcode() == ISD::FMUL)
7690             return DAG.getNode(PreferredFusedOpcode, SL, VT,
7691                                N0.getOperand(0), N0.getOperand(1),
7692                                DAG.getNode(PreferredFusedOpcode, SL, VT,
7693                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7694                                                        N020.getOperand(0)),
7695                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7696                                                        N020.getOperand(1)),
7697                                            DAG.getNode(ISD::FNEG, SL, VT,
7698                                                        N1)));
7699         }
7700       }
7701
7702       // fold (fsub (fpext (fma x, y, (fmul u, v))), z)
7703       //   -> (fma (fpext x), (fpext y),
7704       //           (fma (fpext u), (fpext v), (fneg z)))
7705       // FIXME: This turns two single-precision and one double-precision
7706       // operation into two double-precision operations, which might not be
7707       // interesting for all targets, especially GPUs.
7708       if (N0.getOpcode() == ISD::FP_EXTEND) {
7709         SDValue N00 = N0.getOperand(0);
7710         if (N00.getOpcode() == PreferredFusedOpcode) {
7711           SDValue N002 = N00.getOperand(2);
7712           if (N002.getOpcode() == ISD::FMUL)
7713             return DAG.getNode(PreferredFusedOpcode, SL, VT,
7714                                DAG.getNode(ISD::FP_EXTEND, SL, VT,
7715                                            N00.getOperand(0)),
7716                                DAG.getNode(ISD::FP_EXTEND, SL, VT,
7717                                            N00.getOperand(1)),
7718                                DAG.getNode(PreferredFusedOpcode, SL, VT,
7719                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7720                                                        N002.getOperand(0)),
7721                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7722                                                        N002.getOperand(1)),
7723                                            DAG.getNode(ISD::FNEG, SL, VT,
7724                                                        N1)));
7725         }
7726       }
7727
7728       // fold (fsub x, (fma y, z, (fpext (fmul u, v))))
7729       //   -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x))
7730       if (N1.getOpcode() == PreferredFusedOpcode &&
7731         N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) {
7732         SDValue N120 = N1.getOperand(2).getOperand(0);
7733         if (N120.getOpcode() == ISD::FMUL) {
7734           SDValue N1200 = N120.getOperand(0);
7735           SDValue N1201 = N120.getOperand(1);
7736           return DAG.getNode(PreferredFusedOpcode, SL, VT,
7737                              DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)),
7738                              N1.getOperand(1),
7739                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7740                                          DAG.getNode(ISD::FNEG, SL, VT,
7741                                              DAG.getNode(ISD::FP_EXTEND, SL,
7742                                                          VT, N1200)),
7743                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7744                                                      N1201),
7745                                          N0));
7746         }
7747       }
7748
7749       // fold (fsub x, (fpext (fma y, z, (fmul u, v))))
7750       //   -> (fma (fneg (fpext y)), (fpext z),
7751       //           (fma (fneg (fpext u)), (fpext v), x))
7752       // FIXME: This turns two single-precision and one double-precision
7753       // operation into two double-precision operations, which might not be
7754       // interesting for all targets, especially GPUs.
7755       if (N1.getOpcode() == ISD::FP_EXTEND &&
7756         N1.getOperand(0).getOpcode() == PreferredFusedOpcode) {
7757         SDValue N100 = N1.getOperand(0).getOperand(0);
7758         SDValue N101 = N1.getOperand(0).getOperand(1);
7759         SDValue N102 = N1.getOperand(0).getOperand(2);
7760         if (N102.getOpcode() == ISD::FMUL) {
7761           SDValue N1020 = N102.getOperand(0);
7762           SDValue N1021 = N102.getOperand(1);
7763           return DAG.getNode(PreferredFusedOpcode, SL, VT,
7764                              DAG.getNode(ISD::FNEG, SL, VT,
7765                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7766                                                      N100)),
7767                              DAG.getNode(ISD::FP_EXTEND, SL, VT, N101),
7768                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7769                                          DAG.getNode(ISD::FNEG, SL, VT,
7770                                              DAG.getNode(ISD::FP_EXTEND, SL,
7771                                                          VT, N1020)),
7772                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7773                                                      N1021),
7774                                          N0));
7775         }
7776       }
7777     }
7778   }
7779
7780   return SDValue();
7781 }
7782
7783 SDValue DAGCombiner::visitFADD(SDNode *N) {
7784   SDValue N0 = N->getOperand(0);
7785   SDValue N1 = N->getOperand(1);
7786   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7787   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7788   EVT VT = N->getValueType(0);
7789   SDLoc DL(N);
7790   const TargetOptions &Options = DAG.getTarget().Options;
7791
7792   // fold vector ops
7793   if (VT.isVector())
7794     if (SDValue FoldedVOp = SimplifyVBinOp(N))
7795       return FoldedVOp;
7796
7797   // fold (fadd c1, c2) -> c1 + c2
7798   if (N0CFP && N1CFP)
7799     return DAG.getNode(ISD::FADD, DL, VT, N0, N1);
7800
7801   // canonicalize constant to RHS
7802   if (N0CFP && !N1CFP)
7803     return DAG.getNode(ISD::FADD, DL, VT, N1, N0);
7804
7805   // fold (fadd A, (fneg B)) -> (fsub A, B)
7806   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
7807       isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
7808     return DAG.getNode(ISD::FSUB, DL, VT, N0,
7809                        GetNegatedExpression(N1, DAG, LegalOperations));
7810
7811   // fold (fadd (fneg A), B) -> (fsub B, A)
7812   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
7813       isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
7814     return DAG.getNode(ISD::FSUB, DL, VT, N1,
7815                        GetNegatedExpression(N0, DAG, LegalOperations));
7816
7817   // If 'unsafe math' is enabled, fold lots of things.
7818   if (Options.UnsafeFPMath) {
7819     // No FP constant should be created after legalization as Instruction
7820     // Selection pass has a hard time dealing with FP constants.
7821     bool AllowNewConst = (Level < AfterLegalizeDAG);
7822
7823     // fold (fadd A, 0) -> A
7824     if (N1CFP && N1CFP->getValueAPF().isZero())
7825       return N0;
7826
7827     // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
7828     if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
7829         isa<ConstantFPSDNode>(N0.getOperand(1)))
7830       return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0),
7831                          DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1));
7832
7833     // If allowed, fold (fadd (fneg x), x) -> 0.0
7834     if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
7835       return DAG.getConstantFP(0.0, DL, VT);
7836
7837     // If allowed, fold (fadd x, (fneg x)) -> 0.0
7838     if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
7839       return DAG.getConstantFP(0.0, DL, VT);
7840
7841     // We can fold chains of FADD's of the same value into multiplications.
7842     // This transform is not safe in general because we are reducing the number
7843     // of rounding steps.
7844     if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
7845       if (N0.getOpcode() == ISD::FMUL) {
7846         ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
7847         ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
7848
7849         // (fadd (fmul x, c), x) -> (fmul x, c+1)
7850         if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
7851           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP01, 0),
7852                                        DAG.getConstantFP(1.0, DL, VT));
7853           return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP);
7854         }
7855
7856         // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
7857         if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
7858             N1.getOperand(0) == N1.getOperand(1) &&
7859             N0.getOperand(0) == N1.getOperand(0)) {
7860           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP01, 0),
7861                                        DAG.getConstantFP(2.0, DL, VT));
7862           return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP);
7863         }
7864       }
7865
7866       if (N1.getOpcode() == ISD::FMUL) {
7867         ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
7868         ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
7869
7870         // (fadd x, (fmul x, c)) -> (fmul x, c+1)
7871         if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
7872           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP11, 0),
7873                                        DAG.getConstantFP(1.0, DL, VT));
7874           return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP);
7875         }
7876
7877         // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
7878         if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
7879             N0.getOperand(0) == N0.getOperand(1) &&
7880             N1.getOperand(0) == N0.getOperand(0)) {
7881           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP11, 0),
7882                                        DAG.getConstantFP(2.0, DL, VT));
7883           return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP);
7884         }
7885       }
7886
7887       if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
7888         ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
7889         // (fadd (fadd x, x), x) -> (fmul x, 3.0)
7890         if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
7891             (N0.getOperand(0) == N1)) {
7892           return DAG.getNode(ISD::FMUL, DL, VT,
7893                              N1, DAG.getConstantFP(3.0, DL, VT));
7894         }
7895       }
7896
7897       if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
7898         ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
7899         // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
7900         if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
7901             N1.getOperand(0) == N0) {
7902           return DAG.getNode(ISD::FMUL, DL, VT,
7903                              N0, DAG.getConstantFP(3.0, DL, VT));
7904         }
7905       }
7906
7907       // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
7908       if (AllowNewConst &&
7909           N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
7910           N0.getOperand(0) == N0.getOperand(1) &&
7911           N1.getOperand(0) == N1.getOperand(1) &&
7912           N0.getOperand(0) == N1.getOperand(0)) {
7913         return DAG.getNode(ISD::FMUL, DL, VT,
7914                            N0.getOperand(0), DAG.getConstantFP(4.0, DL, VT));
7915       }
7916     }
7917   } // enable-unsafe-fp-math
7918
7919   // FADD -> FMA combines:
7920   SDValue Fused = visitFADDForFMACombine(N);
7921   if (Fused) {
7922     AddToWorklist(Fused.getNode());
7923     return Fused;
7924   }
7925
7926   return SDValue();
7927 }
7928
7929 SDValue DAGCombiner::visitFSUB(SDNode *N) {
7930   SDValue N0 = N->getOperand(0);
7931   SDValue N1 = N->getOperand(1);
7932   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
7933   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
7934   EVT VT = N->getValueType(0);
7935   SDLoc dl(N);
7936   const TargetOptions &Options = DAG.getTarget().Options;
7937
7938   // fold vector ops
7939   if (VT.isVector())
7940     if (SDValue FoldedVOp = SimplifyVBinOp(N))
7941       return FoldedVOp;
7942
7943   // fold (fsub c1, c2) -> c1-c2
7944   if (N0CFP && N1CFP)
7945     return DAG.getNode(ISD::FSUB, dl, VT, N0, N1);
7946
7947   // fold (fsub A, (fneg B)) -> (fadd A, B)
7948   if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
7949     return DAG.getNode(ISD::FADD, dl, VT, N0,
7950                        GetNegatedExpression(N1, DAG, LegalOperations));
7951
7952   // If 'unsafe math' is enabled, fold lots of things.
7953   if (Options.UnsafeFPMath) {
7954     // (fsub A, 0) -> A
7955     if (N1CFP && N1CFP->getValueAPF().isZero())
7956       return N0;
7957
7958     // (fsub 0, B) -> -B
7959     if (N0CFP && N0CFP->getValueAPF().isZero()) {
7960       if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
7961         return GetNegatedExpression(N1, DAG, LegalOperations);
7962       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
7963         return DAG.getNode(ISD::FNEG, dl, VT, N1);
7964     }
7965
7966     // (fsub x, x) -> 0.0
7967     if (N0 == N1)
7968       return DAG.getConstantFP(0.0f, dl, VT);
7969
7970     // (fsub x, (fadd x, y)) -> (fneg y)
7971     // (fsub x, (fadd y, x)) -> (fneg y)
7972     if (N1.getOpcode() == ISD::FADD) {
7973       SDValue N10 = N1->getOperand(0);
7974       SDValue N11 = N1->getOperand(1);
7975
7976       if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
7977         return GetNegatedExpression(N11, DAG, LegalOperations);
7978
7979       if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
7980         return GetNegatedExpression(N10, DAG, LegalOperations);
7981     }
7982   }
7983
7984   // FSUB -> FMA combines:
7985   SDValue Fused = visitFSUBForFMACombine(N);
7986   if (Fused) {
7987     AddToWorklist(Fused.getNode());
7988     return Fused;
7989   }
7990
7991   return SDValue();
7992 }
7993
7994 SDValue DAGCombiner::visitFMUL(SDNode *N) {
7995   SDValue N0 = N->getOperand(0);
7996   SDValue N1 = N->getOperand(1);
7997   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
7998   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
7999   EVT VT = N->getValueType(0);
8000   SDLoc DL(N);
8001   const TargetOptions &Options = DAG.getTarget().Options;
8002
8003   // fold vector ops
8004   if (VT.isVector()) {
8005     // This just handles C1 * C2 for vectors. Other vector folds are below.
8006     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8007       return FoldedVOp;
8008   }
8009
8010   // fold (fmul c1, c2) -> c1*c2
8011   if (N0CFP && N1CFP)
8012     return DAG.getNode(ISD::FMUL, DL, VT, N0, N1);
8013
8014   // canonicalize constant to RHS
8015   if (isConstantFPBuildVectorOrConstantFP(N0) &&
8016      !isConstantFPBuildVectorOrConstantFP(N1))
8017     return DAG.getNode(ISD::FMUL, DL, VT, N1, N0);
8018
8019   // fold (fmul A, 1.0) -> A
8020   if (N1CFP && N1CFP->isExactlyValue(1.0))
8021     return N0;
8022
8023   if (Options.UnsafeFPMath) {
8024     // fold (fmul A, 0) -> 0
8025     if (N1CFP && N1CFP->getValueAPF().isZero())
8026       return N1;
8027
8028     // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
8029     if (N0.getOpcode() == ISD::FMUL) {
8030       // Fold scalars or any vector constants (not just splats).
8031       // This fold is done in general by InstCombine, but extra fmul insts
8032       // may have been generated during lowering.
8033       SDValue N00 = N0.getOperand(0);
8034       SDValue N01 = N0.getOperand(1);
8035       auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
8036       auto *BV00 = dyn_cast<BuildVectorSDNode>(N00);
8037       auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
8038       
8039       // Check 1: Make sure that the first operand of the inner multiply is NOT
8040       // a constant. Otherwise, we may induce infinite looping.
8041       if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) {
8042         // Check 2: Make sure that the second operand of the inner multiply and
8043         // the second operand of the outer multiply are constants.
8044         if ((N1CFP && isConstOrConstSplatFP(N01)) ||
8045             (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
8046           SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1);
8047           return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts);
8048         }
8049       }
8050     }
8051
8052     // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
8053     // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
8054     // during an early run of DAGCombiner can prevent folding with fmuls
8055     // inserted during lowering.
8056     if (N0.getOpcode() == ISD::FADD && N0.getOperand(0) == N0.getOperand(1)) {
8057       const SDValue Two = DAG.getConstantFP(2.0, DL, VT);
8058       SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1);
8059       return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts);
8060     }
8061   }
8062
8063   // fold (fmul X, 2.0) -> (fadd X, X)
8064   if (N1CFP && N1CFP->isExactlyValue(+2.0))
8065     return DAG.getNode(ISD::FADD, DL, VT, N0, N0);
8066
8067   // fold (fmul X, -1.0) -> (fneg X)
8068   if (N1CFP && N1CFP->isExactlyValue(-1.0))
8069     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8070       return DAG.getNode(ISD::FNEG, DL, VT, N0);
8071
8072   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
8073   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8074     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8075       // Both can be negated for free, check to see if at least one is cheaper
8076       // negated.
8077       if (LHSNeg == 2 || RHSNeg == 2)
8078         return DAG.getNode(ISD::FMUL, DL, VT,
8079                            GetNegatedExpression(N0, DAG, LegalOperations),
8080                            GetNegatedExpression(N1, DAG, LegalOperations));
8081     }
8082   }
8083
8084   return SDValue();
8085 }
8086
8087 SDValue DAGCombiner::visitFMA(SDNode *N) {
8088   SDValue N0 = N->getOperand(0);
8089   SDValue N1 = N->getOperand(1);
8090   SDValue N2 = N->getOperand(2);
8091   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8092   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8093   EVT VT = N->getValueType(0);
8094   SDLoc dl(N);
8095   const TargetOptions &Options = DAG.getTarget().Options;
8096
8097   // Constant fold FMA.
8098   if (isa<ConstantFPSDNode>(N0) &&
8099       isa<ConstantFPSDNode>(N1) &&
8100       isa<ConstantFPSDNode>(N2)) {
8101     return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
8102   }
8103
8104   if (Options.UnsafeFPMath) {
8105     if (N0CFP && N0CFP->isZero())
8106       return N2;
8107     if (N1CFP && N1CFP->isZero())
8108       return N2;
8109   }
8110   if (N0CFP && N0CFP->isExactlyValue(1.0))
8111     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
8112   if (N1CFP && N1CFP->isExactlyValue(1.0))
8113     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
8114
8115   // Canonicalize (fma c, x, y) -> (fma x, c, y)
8116   if (N0CFP && !N1CFP)
8117     return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
8118
8119   // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
8120   if (Options.UnsafeFPMath && N1CFP &&
8121       N2.getOpcode() == ISD::FMUL &&
8122       N0 == N2.getOperand(0) &&
8123       N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
8124     return DAG.getNode(ISD::FMUL, dl, VT, N0,
8125                        DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
8126   }
8127
8128
8129   // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
8130   if (Options.UnsafeFPMath &&
8131       N0.getOpcode() == ISD::FMUL && N1CFP &&
8132       N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
8133     return DAG.getNode(ISD::FMA, dl, VT,
8134                        N0.getOperand(0),
8135                        DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
8136                        N2);
8137   }
8138
8139   // (fma x, 1, y) -> (fadd x, y)
8140   // (fma x, -1, y) -> (fadd (fneg x), y)
8141   if (N1CFP) {
8142     if (N1CFP->isExactlyValue(1.0))
8143       return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
8144
8145     if (N1CFP->isExactlyValue(-1.0) &&
8146         (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
8147       SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
8148       AddToWorklist(RHSNeg.getNode());
8149       return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
8150     }
8151   }
8152
8153   // (fma x, c, x) -> (fmul x, (c+1))
8154   if (Options.UnsafeFPMath && N1CFP && N0 == N2)
8155     return DAG.getNode(ISD::FMUL, dl, VT, N0,
8156                        DAG.getNode(ISD::FADD, dl, VT,
8157                                    N1, DAG.getConstantFP(1.0, dl, VT)));
8158
8159   // (fma x, c, (fneg x)) -> (fmul x, (c-1))
8160   if (Options.UnsafeFPMath && N1CFP &&
8161       N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
8162     return DAG.getNode(ISD::FMUL, dl, VT, N0,
8163                        DAG.getNode(ISD::FADD, dl, VT,
8164                                    N1, DAG.getConstantFP(-1.0, dl, VT)));
8165
8166
8167   return SDValue();
8168 }
8169
8170 SDValue DAGCombiner::visitFDIV(SDNode *N) {
8171   SDValue N0 = N->getOperand(0);
8172   SDValue N1 = N->getOperand(1);
8173   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8174   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8175   EVT VT = N->getValueType(0);
8176   SDLoc DL(N);
8177   const TargetOptions &Options = DAG.getTarget().Options;
8178
8179   // fold vector ops
8180   if (VT.isVector())
8181     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8182       return FoldedVOp;
8183
8184   // fold (fdiv c1, c2) -> c1/c2
8185   if (N0CFP && N1CFP)
8186     return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
8187
8188   if (Options.UnsafeFPMath) {
8189     // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
8190     if (N1CFP) {
8191       // Compute the reciprocal 1.0 / c2.
8192       APFloat N1APF = N1CFP->getValueAPF();
8193       APFloat Recip(N1APF.getSemantics(), 1); // 1.0
8194       APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
8195       // Only do the transform if the reciprocal is a legal fp immediate that
8196       // isn't too nasty (eg NaN, denormal, ...).
8197       if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
8198           (!LegalOperations ||
8199            // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
8200            // backend)... we should handle this gracefully after Legalize.
8201            // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
8202            TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
8203            TLI.isFPImmLegal(Recip, VT)))
8204         return DAG.getNode(ISD::FMUL, DL, VT, N0,
8205                            DAG.getConstantFP(Recip, DL, VT));
8206     }
8207
8208     // If this FDIV is part of a reciprocal square root, it may be folded
8209     // into a target-specific square root estimate instruction.
8210     if (N1.getOpcode() == ISD::FSQRT) {
8211       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0))) {
8212         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8213       }
8214     } else if (N1.getOpcode() == ISD::FP_EXTEND &&
8215                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8216       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
8217         RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
8218         AddToWorklist(RV.getNode());
8219         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8220       }
8221     } else if (N1.getOpcode() == ISD::FP_ROUND &&
8222                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8223       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
8224         RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
8225         AddToWorklist(RV.getNode());
8226         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8227       }
8228     } else if (N1.getOpcode() == ISD::FMUL) {
8229       // Look through an FMUL. Even though this won't remove the FDIV directly,
8230       // it's still worthwhile to get rid of the FSQRT if possible.
8231       SDValue SqrtOp;
8232       SDValue OtherOp;
8233       if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8234         SqrtOp = N1.getOperand(0);
8235         OtherOp = N1.getOperand(1);
8236       } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
8237         SqrtOp = N1.getOperand(1);
8238         OtherOp = N1.getOperand(0);
8239       }
8240       if (SqrtOp.getNode()) {
8241         // We found a FSQRT, so try to make this fold:
8242         // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
8243         if (SDValue RV = BuildRsqrtEstimate(SqrtOp.getOperand(0))) {
8244           RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp);
8245           AddToWorklist(RV.getNode());
8246           return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8247         }
8248       }
8249     }
8250
8251     // Fold into a reciprocal estimate and multiply instead of a real divide.
8252     if (SDValue RV = BuildReciprocalEstimate(N1)) {
8253       AddToWorklist(RV.getNode());
8254       return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8255     }
8256   }
8257
8258   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
8259   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8260     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8261       // Both can be negated for free, check to see if at least one is cheaper
8262       // negated.
8263       if (LHSNeg == 2 || RHSNeg == 2)
8264         return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
8265                            GetNegatedExpression(N0, DAG, LegalOperations),
8266                            GetNegatedExpression(N1, DAG, LegalOperations));
8267     }
8268   }
8269
8270   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
8271   // reciprocal.
8272   // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
8273   // Notice that this is not always beneficial. One reason is different target
8274   // may have different costs for FDIV and FMUL, so sometimes the cost of two
8275   // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
8276   // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
8277   if (Options.UnsafeFPMath) {
8278     // Skip if current node is a reciprocal.
8279     if (N0CFP && N0CFP->isExactlyValue(1.0))
8280       return SDValue();
8281
8282     SmallVector<SDNode *, 4> Users;
8283     // Find all FDIV users of the same divisor.
8284     for (SDNode::use_iterator UI = N1.getNode()->use_begin(),
8285                               UE = N1.getNode()->use_end();
8286          UI != UE; ++UI) {
8287       SDNode *User = UI.getUse().getUser();
8288       if (User->getOpcode() == ISD::FDIV && User->getOperand(1) == N1)
8289         Users.push_back(User);
8290     }
8291
8292     if (TLI.combineRepeatedFPDivisors(Users.size())) {
8293       SDLoc DL(N);
8294       SDValue FPOne = DAG.getConstantFP(1.0, DL, VT); // floating point 1.0
8295       SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1);
8296
8297       // Dividend / Divisor -> Dividend * Reciprocal
8298       for (auto I = Users.begin(), E = Users.end(); I != E; ++I) {
8299         if ((*I)->getOperand(0) != FPOne) {
8300           SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(*I), VT,
8301                                         (*I)->getOperand(0), Reciprocal);
8302           DAG.ReplaceAllUsesWith(*I, NewNode.getNode());
8303         }
8304       }
8305       return SDValue();
8306     }
8307   }
8308
8309   return SDValue();
8310 }
8311
8312 SDValue DAGCombiner::visitFREM(SDNode *N) {
8313   SDValue N0 = N->getOperand(0);
8314   SDValue N1 = N->getOperand(1);
8315   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8316   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8317   EVT VT = N->getValueType(0);
8318
8319   // fold (frem c1, c2) -> fmod(c1,c2)
8320   if (N0CFP && N1CFP)
8321     return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
8322
8323   return SDValue();
8324 }
8325
8326 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
8327   if (DAG.getTarget().Options.UnsafeFPMath &&
8328       !TLI.isFsqrtCheap()) {
8329     // Compute this as X * (1/sqrt(X)) = X * (X ** -0.5)
8330     if (SDValue RV = BuildRsqrtEstimate(N->getOperand(0))) {
8331       EVT VT = RV.getValueType();
8332       SDLoc DL(N);
8333       RV = DAG.getNode(ISD::FMUL, DL, VT, N->getOperand(0), RV);
8334       AddToWorklist(RV.getNode());
8335
8336       // Unfortunately, RV is now NaN if the input was exactly 0.
8337       // Select out this case and force the answer to 0.
8338       SDValue Zero = DAG.getConstantFP(0.0, DL, VT);
8339       SDValue ZeroCmp =
8340         DAG.getSetCC(DL, TLI.getSetCCResultType(*DAG.getContext(), VT),
8341                      N->getOperand(0), Zero, ISD::SETEQ);
8342       AddToWorklist(ZeroCmp.getNode());
8343       AddToWorklist(RV.getNode());
8344
8345       RV = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT,
8346                        DL, VT, ZeroCmp, Zero, RV);
8347       return RV;
8348     }
8349   }
8350   return SDValue();
8351 }
8352
8353 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
8354   SDValue N0 = N->getOperand(0);
8355   SDValue N1 = N->getOperand(1);
8356   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8357   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8358   EVT VT = N->getValueType(0);
8359
8360   if (N0CFP && N1CFP)  // Constant fold
8361     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
8362
8363   if (N1CFP) {
8364     const APFloat& V = N1CFP->getValueAPF();
8365     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
8366     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
8367     if (!V.isNegative()) {
8368       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
8369         return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8370     } else {
8371       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8372         return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
8373                            DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
8374     }
8375   }
8376
8377   // copysign(fabs(x), y) -> copysign(x, y)
8378   // copysign(fneg(x), y) -> copysign(x, y)
8379   // copysign(copysign(x,z), y) -> copysign(x, y)
8380   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
8381       N0.getOpcode() == ISD::FCOPYSIGN)
8382     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8383                        N0.getOperand(0), N1);
8384
8385   // copysign(x, abs(y)) -> abs(x)
8386   if (N1.getOpcode() == ISD::FABS)
8387     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8388
8389   // copysign(x, copysign(y,z)) -> copysign(x, z)
8390   if (N1.getOpcode() == ISD::FCOPYSIGN)
8391     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8392                        N0, N1.getOperand(1));
8393
8394   // copysign(x, fp_extend(y)) -> copysign(x, y)
8395   // copysign(x, fp_round(y)) -> copysign(x, y)
8396   if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
8397     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8398                        N0, N1.getOperand(0));
8399
8400   return SDValue();
8401 }
8402
8403 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
8404   SDValue N0 = N->getOperand(0);
8405   EVT VT = N->getValueType(0);
8406   EVT OpVT = N0.getValueType();
8407
8408   // fold (sint_to_fp c1) -> c1fp
8409   if (isConstantIntBuildVectorOrConstantInt(N0) &&
8410       // ...but only if the target supports immediate floating-point values
8411       (!LegalOperations ||
8412        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
8413     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
8414
8415   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
8416   // but UINT_TO_FP is legal on this target, try to convert.
8417   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
8418       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
8419     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
8420     if (DAG.SignBitIsZero(N0))
8421       return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
8422   }
8423
8424   // The next optimizations are desirable only if SELECT_CC can be lowered.
8425   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
8426     // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
8427     if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
8428         !VT.isVector() &&
8429         (!LegalOperations ||
8430          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8431       SDLoc DL(N);
8432       SDValue Ops[] =
8433         { N0.getOperand(0), N0.getOperand(1),
8434           DAG.getConstantFP(-1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8435           N0.getOperand(2) };
8436       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8437     }
8438
8439     // fold (sint_to_fp (zext (setcc x, y, cc))) ->
8440     //      (select_cc x, y, 1.0, 0.0,, cc)
8441     if (N0.getOpcode() == ISD::ZERO_EXTEND &&
8442         N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
8443         (!LegalOperations ||
8444          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8445       SDLoc DL(N);
8446       SDValue Ops[] =
8447         { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
8448           DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8449           N0.getOperand(0).getOperand(2) };
8450       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8451     }
8452   }
8453
8454   return SDValue();
8455 }
8456
8457 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
8458   SDValue N0 = N->getOperand(0);
8459   EVT VT = N->getValueType(0);
8460   EVT OpVT = N0.getValueType();
8461
8462   // fold (uint_to_fp c1) -> c1fp
8463   if (isConstantIntBuildVectorOrConstantInt(N0) &&
8464       // ...but only if the target supports immediate floating-point values
8465       (!LegalOperations ||
8466        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
8467     return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
8468
8469   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
8470   // but SINT_TO_FP is legal on this target, try to convert.
8471   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
8472       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
8473     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
8474     if (DAG.SignBitIsZero(N0))
8475       return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
8476   }
8477
8478   // The next optimizations are desirable only if SELECT_CC can be lowered.
8479   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
8480     // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
8481
8482     if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
8483         (!LegalOperations ||
8484          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8485       SDLoc DL(N);
8486       SDValue Ops[] =
8487         { N0.getOperand(0), N0.getOperand(1),
8488           DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8489           N0.getOperand(2) };
8490       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8491     }
8492   }
8493
8494   return SDValue();
8495 }
8496
8497 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x
8498 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) {
8499   SDValue N0 = N->getOperand(0);
8500   EVT VT = N->getValueType(0);
8501
8502   if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP)
8503     return SDValue();
8504
8505   SDValue Src = N0.getOperand(0);
8506   EVT SrcVT = Src.getValueType();
8507   bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP;
8508   bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT;
8509
8510   // We can safely assume the conversion won't overflow the output range,
8511   // because (for example) (uint8_t)18293.f is undefined behavior.
8512
8513   // Since we can assume the conversion won't overflow, our decision as to
8514   // whether the input will fit in the float should depend on the minimum
8515   // of the input range and output range.
8516
8517   // This means this is also safe for a signed input and unsigned output, since
8518   // a negative input would lead to undefined behavior.
8519   unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned;
8520   unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned;
8521   unsigned ActualSize = std::min(InputSize, OutputSize);
8522   const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType());
8523
8524   // We can only fold away the float conversion if the input range can be
8525   // represented exactly in the float range.
8526   if (APFloat::semanticsPrecision(sem) >= ActualSize) {
8527     if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) {
8528       unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND
8529                                                        : ISD::ZERO_EXTEND;
8530       return DAG.getNode(ExtOp, SDLoc(N), VT, Src);
8531     }
8532     if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits())
8533       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src);
8534     if (SrcVT == VT)
8535       return Src;
8536     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Src);
8537   }
8538   return SDValue();
8539 }
8540
8541 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
8542   SDValue N0 = N->getOperand(0);
8543   EVT VT = N->getValueType(0);
8544
8545   // fold (fp_to_sint c1fp) -> c1
8546   if (isConstantFPBuildVectorOrConstantFP(N0))
8547     return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
8548
8549   return FoldIntToFPToInt(N, DAG);
8550 }
8551
8552 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
8553   SDValue N0 = N->getOperand(0);
8554   EVT VT = N->getValueType(0);
8555
8556   // fold (fp_to_uint c1fp) -> c1
8557   if (isConstantFPBuildVectorOrConstantFP(N0))
8558     return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
8559
8560   return FoldIntToFPToInt(N, DAG);
8561 }
8562
8563 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
8564   SDValue N0 = N->getOperand(0);
8565   SDValue N1 = N->getOperand(1);
8566   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8567   EVT VT = N->getValueType(0);
8568
8569   // fold (fp_round c1fp) -> c1fp
8570   if (N0CFP)
8571     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
8572
8573   // fold (fp_round (fp_extend x)) -> x
8574   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
8575     return N0.getOperand(0);
8576
8577   // fold (fp_round (fp_round x)) -> (fp_round x)
8578   if (N0.getOpcode() == ISD::FP_ROUND) {
8579     const bool NIsTrunc = N->getConstantOperandVal(1) == 1;
8580     const bool N0IsTrunc = N0.getNode()->getConstantOperandVal(1) == 1;
8581     // If the first fp_round isn't a value preserving truncation, it might
8582     // introduce a tie in the second fp_round, that wouldn't occur in the
8583     // single-step fp_round we want to fold to.
8584     // In other words, double rounding isn't the same as rounding.
8585     // Also, this is a value preserving truncation iff both fp_round's are.
8586     if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) {
8587       SDLoc DL(N);
8588       return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0),
8589                          DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL));
8590     }
8591   }
8592
8593   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
8594   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
8595     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
8596                               N0.getOperand(0), N1);
8597     AddToWorklist(Tmp.getNode());
8598     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8599                        Tmp, N0.getOperand(1));
8600   }
8601
8602   return SDValue();
8603 }
8604
8605 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
8606   SDValue N0 = N->getOperand(0);
8607   EVT VT = N->getValueType(0);
8608   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
8609   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8610
8611   // fold (fp_round_inreg c1fp) -> c1fp
8612   if (N0CFP && isTypeLegal(EVT)) {
8613     SDLoc DL(N);
8614     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), DL, EVT);
8615     return DAG.getNode(ISD::FP_EXTEND, DL, VT, Round);
8616   }
8617
8618   return SDValue();
8619 }
8620
8621 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
8622   SDValue N0 = N->getOperand(0);
8623   EVT VT = N->getValueType(0);
8624
8625   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
8626   if (N->hasOneUse() &&
8627       N->use_begin()->getOpcode() == ISD::FP_ROUND)
8628     return SDValue();
8629
8630   // fold (fp_extend c1fp) -> c1fp
8631   if (isConstantFPBuildVectorOrConstantFP(N0))
8632     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
8633
8634   // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op)
8635   if (N0.getOpcode() == ISD::FP16_TO_FP &&
8636       TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal)
8637     return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0));
8638
8639   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
8640   // value of X.
8641   if (N0.getOpcode() == ISD::FP_ROUND
8642       && N0.getNode()->getConstantOperandVal(1) == 1) {
8643     SDValue In = N0.getOperand(0);
8644     if (In.getValueType() == VT) return In;
8645     if (VT.bitsLT(In.getValueType()))
8646       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
8647                          In, N0.getOperand(1));
8648     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
8649   }
8650
8651   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
8652   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8653        TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
8654     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8655     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
8656                                      LN0->getChain(),
8657                                      LN0->getBasePtr(), N0.getValueType(),
8658                                      LN0->getMemOperand());
8659     CombineTo(N, ExtLoad);
8660     CombineTo(N0.getNode(),
8661               DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
8662                           N0.getValueType(), ExtLoad,
8663                           DAG.getIntPtrConstant(1, SDLoc(N0))),
8664               ExtLoad.getValue(1));
8665     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8666   }
8667
8668   return SDValue();
8669 }
8670
8671 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
8672   SDValue N0 = N->getOperand(0);
8673   EVT VT = N->getValueType(0);
8674
8675   // fold (fceil c1) -> fceil(c1)
8676   if (isConstantFPBuildVectorOrConstantFP(N0))
8677     return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
8678
8679   return SDValue();
8680 }
8681
8682 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
8683   SDValue N0 = N->getOperand(0);
8684   EVT VT = N->getValueType(0);
8685
8686   // fold (ftrunc c1) -> ftrunc(c1)
8687   if (isConstantFPBuildVectorOrConstantFP(N0))
8688     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
8689
8690   return SDValue();
8691 }
8692
8693 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
8694   SDValue N0 = N->getOperand(0);
8695   EVT VT = N->getValueType(0);
8696
8697   // fold (ffloor c1) -> ffloor(c1)
8698   if (isConstantFPBuildVectorOrConstantFP(N0))
8699     return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
8700
8701   return SDValue();
8702 }
8703
8704 // FIXME: FNEG and FABS have a lot in common; refactor.
8705 SDValue DAGCombiner::visitFNEG(SDNode *N) {
8706   SDValue N0 = N->getOperand(0);
8707   EVT VT = N->getValueType(0);
8708
8709   // Constant fold FNEG.
8710   if (isConstantFPBuildVectorOrConstantFP(N0))
8711     return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
8712
8713   if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
8714                          &DAG.getTarget().Options))
8715     return GetNegatedExpression(N0, DAG, LegalOperations);
8716
8717   // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
8718   // constant pool values.
8719   if (!TLI.isFNegFree(VT) &&
8720       N0.getOpcode() == ISD::BITCAST &&
8721       N0.getNode()->hasOneUse()) {
8722     SDValue Int = N0.getOperand(0);
8723     EVT IntVT = Int.getValueType();
8724     if (IntVT.isInteger() && !IntVT.isVector()) {
8725       APInt SignMask;
8726       if (N0.getValueType().isVector()) {
8727         // For a vector, get a mask such as 0x80... per scalar element
8728         // and splat it.
8729         SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
8730         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
8731       } else {
8732         // For a scalar, just generate 0x80...
8733         SignMask = APInt::getSignBit(IntVT.getSizeInBits());
8734       }
8735       SDLoc DL0(N0);
8736       Int = DAG.getNode(ISD::XOR, DL0, IntVT, Int,
8737                         DAG.getConstant(SignMask, DL0, IntVT));
8738       AddToWorklist(Int.getNode());
8739       return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int);
8740     }
8741   }
8742
8743   // (fneg (fmul c, x)) -> (fmul -c, x)
8744   if (N0.getOpcode() == ISD::FMUL) {
8745     ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
8746     if (CFP1) {
8747       APFloat CVal = CFP1->getValueAPF();
8748       CVal.changeSign();
8749       if (Level >= AfterLegalizeDAG &&
8750           (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
8751            TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
8752         return DAG.getNode(
8753             ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
8754             DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)));
8755     }
8756   }
8757
8758   return SDValue();
8759 }
8760
8761 SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
8762   SDValue N0 = N->getOperand(0);
8763   SDValue N1 = N->getOperand(1);
8764   const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8765   const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8766
8767   if (N0CFP && N1CFP) {
8768     const APFloat &C0 = N0CFP->getValueAPF();
8769     const APFloat &C1 = N1CFP->getValueAPF();
8770     return DAG.getConstantFP(minnum(C0, C1), SDLoc(N), N->getValueType(0));
8771   }
8772
8773   if (N0CFP) {
8774     EVT VT = N->getValueType(0);
8775     // Canonicalize to constant on RHS.
8776     return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
8777   }
8778
8779   return SDValue();
8780 }
8781
8782 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
8783   SDValue N0 = N->getOperand(0);
8784   SDValue N1 = N->getOperand(1);
8785   const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8786   const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8787
8788   if (N0CFP && N1CFP) {
8789     const APFloat &C0 = N0CFP->getValueAPF();
8790     const APFloat &C1 = N1CFP->getValueAPF();
8791     return DAG.getConstantFP(maxnum(C0, C1), SDLoc(N), N->getValueType(0));
8792   }
8793
8794   if (N0CFP) {
8795     EVT VT = N->getValueType(0);
8796     // Canonicalize to constant on RHS.
8797     return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
8798   }
8799
8800   return SDValue();
8801 }
8802
8803 SDValue DAGCombiner::visitFABS(SDNode *N) {
8804   SDValue N0 = N->getOperand(0);
8805   EVT VT = N->getValueType(0);
8806
8807   // fold (fabs c1) -> fabs(c1)
8808   if (isConstantFPBuildVectorOrConstantFP(N0))
8809     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8810
8811   // fold (fabs (fabs x)) -> (fabs x)
8812   if (N0.getOpcode() == ISD::FABS)
8813     return N->getOperand(0);
8814
8815   // fold (fabs (fneg x)) -> (fabs x)
8816   // fold (fabs (fcopysign x, y)) -> (fabs x)
8817   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
8818     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
8819
8820   // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
8821   // constant pool values.
8822   if (!TLI.isFAbsFree(VT) &&
8823       N0.getOpcode() == ISD::BITCAST &&
8824       N0.getNode()->hasOneUse()) {
8825     SDValue Int = N0.getOperand(0);
8826     EVT IntVT = Int.getValueType();
8827     if (IntVT.isInteger() && !IntVT.isVector()) {
8828       APInt SignMask;
8829       if (N0.getValueType().isVector()) {
8830         // For a vector, get a mask such as 0x7f... per scalar element
8831         // and splat it.
8832         SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
8833         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
8834       } else {
8835         // For a scalar, just generate 0x7f...
8836         SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
8837       }
8838       SDLoc DL(N0);
8839       Int = DAG.getNode(ISD::AND, DL, IntVT, Int,
8840                         DAG.getConstant(SignMask, DL, IntVT));
8841       AddToWorklist(Int.getNode());
8842       return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int);
8843     }
8844   }
8845
8846   return SDValue();
8847 }
8848
8849 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
8850   SDValue Chain = N->getOperand(0);
8851   SDValue N1 = N->getOperand(1);
8852   SDValue N2 = N->getOperand(2);
8853
8854   // If N is a constant we could fold this into a fallthrough or unconditional
8855   // branch. However that doesn't happen very often in normal code, because
8856   // Instcombine/SimplifyCFG should have handled the available opportunities.
8857   // If we did this folding here, it would be necessary to update the
8858   // MachineBasicBlock CFG, which is awkward.
8859
8860   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
8861   // on the target.
8862   if (N1.getOpcode() == ISD::SETCC &&
8863       TLI.isOperationLegalOrCustom(ISD::BR_CC,
8864                                    N1.getOperand(0).getValueType())) {
8865     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
8866                        Chain, N1.getOperand(2),
8867                        N1.getOperand(0), N1.getOperand(1), N2);
8868   }
8869
8870   if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
8871       ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
8872        (N1.getOperand(0).hasOneUse() &&
8873         N1.getOperand(0).getOpcode() == ISD::SRL))) {
8874     SDNode *Trunc = nullptr;
8875     if (N1.getOpcode() == ISD::TRUNCATE) {
8876       // Look pass the truncate.
8877       Trunc = N1.getNode();
8878       N1 = N1.getOperand(0);
8879     }
8880
8881     // Match this pattern so that we can generate simpler code:
8882     //
8883     //   %a = ...
8884     //   %b = and i32 %a, 2
8885     //   %c = srl i32 %b, 1
8886     //   brcond i32 %c ...
8887     //
8888     // into
8889     //
8890     //   %a = ...
8891     //   %b = and i32 %a, 2
8892     //   %c = setcc eq %b, 0
8893     //   brcond %c ...
8894     //
8895     // This applies only when the AND constant value has one bit set and the
8896     // SRL constant is equal to the log2 of the AND constant. The back-end is
8897     // smart enough to convert the result into a TEST/JMP sequence.
8898     SDValue Op0 = N1.getOperand(0);
8899     SDValue Op1 = N1.getOperand(1);
8900
8901     if (Op0.getOpcode() == ISD::AND &&
8902         Op1.getOpcode() == ISD::Constant) {
8903       SDValue AndOp1 = Op0.getOperand(1);
8904
8905       if (AndOp1.getOpcode() == ISD::Constant) {
8906         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
8907
8908         if (AndConst.isPowerOf2() &&
8909             cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
8910           SDLoc DL(N);
8911           SDValue SetCC =
8912             DAG.getSetCC(DL,
8913                          getSetCCResultType(Op0.getValueType()),
8914                          Op0, DAG.getConstant(0, DL, Op0.getValueType()),
8915                          ISD::SETNE);
8916
8917           SDValue NewBRCond = DAG.getNode(ISD::BRCOND, DL,
8918                                           MVT::Other, Chain, SetCC, N2);
8919           // Don't add the new BRCond into the worklist or else SimplifySelectCC
8920           // will convert it back to (X & C1) >> C2.
8921           CombineTo(N, NewBRCond, false);
8922           // Truncate is dead.
8923           if (Trunc)
8924             deleteAndRecombine(Trunc);
8925           // Replace the uses of SRL with SETCC
8926           WorklistRemover DeadNodes(*this);
8927           DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
8928           deleteAndRecombine(N1.getNode());
8929           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8930         }
8931       }
8932     }
8933
8934     if (Trunc)
8935       // Restore N1 if the above transformation doesn't match.
8936       N1 = N->getOperand(1);
8937   }
8938
8939   // Transform br(xor(x, y)) -> br(x != y)
8940   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
8941   if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
8942     SDNode *TheXor = N1.getNode();
8943     SDValue Op0 = TheXor->getOperand(0);
8944     SDValue Op1 = TheXor->getOperand(1);
8945     if (Op0.getOpcode() == Op1.getOpcode()) {
8946       // Avoid missing important xor optimizations.
8947       SDValue Tmp = visitXOR(TheXor);
8948       if (Tmp.getNode()) {
8949         if (Tmp.getNode() != TheXor) {
8950           DEBUG(dbgs() << "\nReplacing.8 ";
8951                 TheXor->dump(&DAG);
8952                 dbgs() << "\nWith: ";
8953                 Tmp.getNode()->dump(&DAG);
8954                 dbgs() << '\n');
8955           WorklistRemover DeadNodes(*this);
8956           DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
8957           deleteAndRecombine(TheXor);
8958           return DAG.getNode(ISD::BRCOND, SDLoc(N),
8959                              MVT::Other, Chain, Tmp, N2);
8960         }
8961
8962         // visitXOR has changed XOR's operands or replaced the XOR completely,
8963         // bail out.
8964         return SDValue(N, 0);
8965       }
8966     }
8967
8968     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
8969       bool Equal = false;
8970       if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
8971         if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
8972             Op0.getOpcode() == ISD::XOR) {
8973           TheXor = Op0.getNode();
8974           Equal = true;
8975         }
8976
8977       EVT SetCCVT = N1.getValueType();
8978       if (LegalTypes)
8979         SetCCVT = getSetCCResultType(SetCCVT);
8980       SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
8981                                    SetCCVT,
8982                                    Op0, Op1,
8983                                    Equal ? ISD::SETEQ : ISD::SETNE);
8984       // Replace the uses of XOR with SETCC
8985       WorklistRemover DeadNodes(*this);
8986       DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
8987       deleteAndRecombine(N1.getNode());
8988       return DAG.getNode(ISD::BRCOND, SDLoc(N),
8989                          MVT::Other, Chain, SetCC, N2);
8990     }
8991   }
8992
8993   return SDValue();
8994 }
8995
8996 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
8997 //
8998 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
8999   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
9000   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
9001
9002   // If N is a constant we could fold this into a fallthrough or unconditional
9003   // branch. However that doesn't happen very often in normal code, because
9004   // Instcombine/SimplifyCFG should have handled the available opportunities.
9005   // If we did this folding here, it would be necessary to update the
9006   // MachineBasicBlock CFG, which is awkward.
9007
9008   // Use SimplifySetCC to simplify SETCC's.
9009   SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
9010                                CondLHS, CondRHS, CC->get(), SDLoc(N),
9011                                false);
9012   if (Simp.getNode()) AddToWorklist(Simp.getNode());
9013
9014   // fold to a simpler setcc
9015   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
9016     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
9017                        N->getOperand(0), Simp.getOperand(2),
9018                        Simp.getOperand(0), Simp.getOperand(1),
9019                        N->getOperand(4));
9020
9021   return SDValue();
9022 }
9023
9024 /// Return true if 'Use' is a load or a store that uses N as its base pointer
9025 /// and that N may be folded in the load / store addressing mode.
9026 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
9027                                     SelectionDAG &DAG,
9028                                     const TargetLowering &TLI) {
9029   EVT VT;
9030   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
9031     if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
9032       return false;
9033     VT = LD->getMemoryVT();
9034   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
9035     if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
9036       return false;
9037     VT = ST->getMemoryVT();
9038   } else
9039     return false;
9040
9041   TargetLowering::AddrMode AM;
9042   if (N->getOpcode() == ISD::ADD) {
9043     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9044     if (Offset)
9045       // [reg +/- imm]
9046       AM.BaseOffs = Offset->getSExtValue();
9047     else
9048       // [reg +/- reg]
9049       AM.Scale = 1;
9050   } else if (N->getOpcode() == ISD::SUB) {
9051     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9052     if (Offset)
9053       // [reg +/- imm]
9054       AM.BaseOffs = -Offset->getSExtValue();
9055     else
9056       // [reg +/- reg]
9057       AM.Scale = 1;
9058   } else
9059     return false;
9060
9061   return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
9062 }
9063
9064 /// Try turning a load/store into a pre-indexed load/store when the base
9065 /// pointer is an add or subtract and it has other uses besides the load/store.
9066 /// After the transformation, the new indexed load/store has effectively folded
9067 /// the add/subtract in and all of its other uses are redirected to the
9068 /// new load/store.
9069 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
9070   if (Level < AfterLegalizeDAG)
9071     return false;
9072
9073   bool isLoad = true;
9074   SDValue Ptr;
9075   EVT VT;
9076   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
9077     if (LD->isIndexed())
9078       return false;
9079     VT = LD->getMemoryVT();
9080     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
9081         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
9082       return false;
9083     Ptr = LD->getBasePtr();
9084   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
9085     if (ST->isIndexed())
9086       return false;
9087     VT = ST->getMemoryVT();
9088     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
9089         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
9090       return false;
9091     Ptr = ST->getBasePtr();
9092     isLoad = false;
9093   } else {
9094     return false;
9095   }
9096
9097   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
9098   // out.  There is no reason to make this a preinc/predec.
9099   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
9100       Ptr.getNode()->hasOneUse())
9101     return false;
9102
9103   // Ask the target to do addressing mode selection.
9104   SDValue BasePtr;
9105   SDValue Offset;
9106   ISD::MemIndexedMode AM = ISD::UNINDEXED;
9107   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
9108     return false;
9109
9110   // Backends without true r+i pre-indexed forms may need to pass a
9111   // constant base with a variable offset so that constant coercion
9112   // will work with the patterns in canonical form.
9113   bool Swapped = false;
9114   if (isa<ConstantSDNode>(BasePtr)) {
9115     std::swap(BasePtr, Offset);
9116     Swapped = true;
9117   }
9118
9119   // Don't create a indexed load / store with zero offset.
9120   if (isNullConstant(Offset))
9121     return false;
9122
9123   // Try turning it into a pre-indexed load / store except when:
9124   // 1) The new base ptr is a frame index.
9125   // 2) If N is a store and the new base ptr is either the same as or is a
9126   //    predecessor of the value being stored.
9127   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
9128   //    that would create a cycle.
9129   // 4) All uses are load / store ops that use it as old base ptr.
9130
9131   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
9132   // (plus the implicit offset) to a register to preinc anyway.
9133   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9134     return false;
9135
9136   // Check #2.
9137   if (!isLoad) {
9138     SDValue Val = cast<StoreSDNode>(N)->getValue();
9139     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
9140       return false;
9141   }
9142
9143   // If the offset is a constant, there may be other adds of constants that
9144   // can be folded with this one. We should do this to avoid having to keep
9145   // a copy of the original base pointer.
9146   SmallVector<SDNode *, 16> OtherUses;
9147   if (isa<ConstantSDNode>(Offset))
9148     for (SDNode::use_iterator UI = BasePtr.getNode()->use_begin(),
9149                               UE = BasePtr.getNode()->use_end();
9150          UI != UE; ++UI) {
9151       SDUse &Use = UI.getUse();
9152       // Skip the use that is Ptr and uses of other results from BasePtr's
9153       // node (important for nodes that return multiple results).
9154       if (Use.getUser() == Ptr.getNode() || Use != BasePtr)
9155         continue;
9156
9157       if (Use.getUser()->isPredecessorOf(N))
9158         continue;
9159
9160       if (Use.getUser()->getOpcode() != ISD::ADD &&
9161           Use.getUser()->getOpcode() != ISD::SUB) {
9162         OtherUses.clear();
9163         break;
9164       }
9165
9166       SDValue Op1 = Use.getUser()->getOperand((UI.getOperandNo() + 1) & 1);
9167       if (!isa<ConstantSDNode>(Op1)) {
9168         OtherUses.clear();
9169         break;
9170       }
9171
9172       // FIXME: In some cases, we can be smarter about this.
9173       if (Op1.getValueType() != Offset.getValueType()) {
9174         OtherUses.clear();
9175         break;
9176       }
9177
9178       OtherUses.push_back(Use.getUser());
9179     }
9180
9181   if (Swapped)
9182     std::swap(BasePtr, Offset);
9183
9184   // Now check for #3 and #4.
9185   bool RealUse = false;
9186
9187   // Caches for hasPredecessorHelper
9188   SmallPtrSet<const SDNode *, 32> Visited;
9189   SmallVector<const SDNode *, 16> Worklist;
9190
9191   for (SDNode *Use : Ptr.getNode()->uses()) {
9192     if (Use == N)
9193       continue;
9194     if (N->hasPredecessorHelper(Use, Visited, Worklist))
9195       return false;
9196
9197     // If Ptr may be folded in addressing mode of other use, then it's
9198     // not profitable to do this transformation.
9199     if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
9200       RealUse = true;
9201   }
9202
9203   if (!RealUse)
9204     return false;
9205
9206   SDValue Result;
9207   if (isLoad)
9208     Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9209                                 BasePtr, Offset, AM);
9210   else
9211     Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9212                                  BasePtr, Offset, AM);
9213   ++PreIndexedNodes;
9214   ++NodesCombined;
9215   DEBUG(dbgs() << "\nReplacing.4 ";
9216         N->dump(&DAG);
9217         dbgs() << "\nWith: ";
9218         Result.getNode()->dump(&DAG);
9219         dbgs() << '\n');
9220   WorklistRemover DeadNodes(*this);
9221   if (isLoad) {
9222     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9223     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9224   } else {
9225     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9226   }
9227
9228   // Finally, since the node is now dead, remove it from the graph.
9229   deleteAndRecombine(N);
9230
9231   if (Swapped)
9232     std::swap(BasePtr, Offset);
9233
9234   // Replace other uses of BasePtr that can be updated to use Ptr
9235   for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
9236     unsigned OffsetIdx = 1;
9237     if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
9238       OffsetIdx = 0;
9239     assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
9240            BasePtr.getNode() && "Expected BasePtr operand");
9241
9242     // We need to replace ptr0 in the following expression:
9243     //   x0 * offset0 + y0 * ptr0 = t0
9244     // knowing that
9245     //   x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
9246     //
9247     // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
9248     // indexed load/store and the expresion that needs to be re-written.
9249     //
9250     // Therefore, we have:
9251     //   t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
9252
9253     ConstantSDNode *CN =
9254       cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
9255     int X0, X1, Y0, Y1;
9256     APInt Offset0 = CN->getAPIntValue();
9257     APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
9258
9259     X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
9260     Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
9261     X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
9262     Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
9263
9264     unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
9265
9266     APInt CNV = Offset0;
9267     if (X0 < 0) CNV = -CNV;
9268     if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
9269     else CNV = CNV - Offset1;
9270
9271     SDLoc DL(OtherUses[i]);
9272
9273     // We can now generate the new expression.
9274     SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0));
9275     SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
9276
9277     SDValue NewUse = DAG.getNode(Opcode,
9278                                  DL,
9279                                  OtherUses[i]->getValueType(0), NewOp1, NewOp2);
9280     DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
9281     deleteAndRecombine(OtherUses[i]);
9282   }
9283
9284   // Replace the uses of Ptr with uses of the updated base value.
9285   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
9286   deleteAndRecombine(Ptr.getNode());
9287
9288   return true;
9289 }
9290
9291 /// Try to combine a load/store with a add/sub of the base pointer node into a
9292 /// post-indexed load/store. The transformation folded the add/subtract into the
9293 /// new indexed load/store effectively and all of its uses are redirected to the
9294 /// new load/store.
9295 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
9296   if (Level < AfterLegalizeDAG)
9297     return false;
9298
9299   bool isLoad = true;
9300   SDValue Ptr;
9301   EVT VT;
9302   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
9303     if (LD->isIndexed())
9304       return false;
9305     VT = LD->getMemoryVT();
9306     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
9307         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
9308       return false;
9309     Ptr = LD->getBasePtr();
9310   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
9311     if (ST->isIndexed())
9312       return false;
9313     VT = ST->getMemoryVT();
9314     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
9315         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
9316       return false;
9317     Ptr = ST->getBasePtr();
9318     isLoad = false;
9319   } else {
9320     return false;
9321   }
9322
9323   if (Ptr.getNode()->hasOneUse())
9324     return false;
9325
9326   for (SDNode *Op : Ptr.getNode()->uses()) {
9327     if (Op == N ||
9328         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
9329       continue;
9330
9331     SDValue BasePtr;
9332     SDValue Offset;
9333     ISD::MemIndexedMode AM = ISD::UNINDEXED;
9334     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
9335       // Don't create a indexed load / store with zero offset.
9336       if (isNullConstant(Offset))
9337         continue;
9338
9339       // Try turning it into a post-indexed load / store except when
9340       // 1) All uses are load / store ops that use it as base ptr (and
9341       //    it may be folded as addressing mmode).
9342       // 2) Op must be independent of N, i.e. Op is neither a predecessor
9343       //    nor a successor of N. Otherwise, if Op is folded that would
9344       //    create a cycle.
9345
9346       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9347         continue;
9348
9349       // Check for #1.
9350       bool TryNext = false;
9351       for (SDNode *Use : BasePtr.getNode()->uses()) {
9352         if (Use == Ptr.getNode())
9353           continue;
9354
9355         // If all the uses are load / store addresses, then don't do the
9356         // transformation.
9357         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
9358           bool RealUse = false;
9359           for (SDNode *UseUse : Use->uses()) {
9360             if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
9361               RealUse = true;
9362           }
9363
9364           if (!RealUse) {
9365             TryNext = true;
9366             break;
9367           }
9368         }
9369       }
9370
9371       if (TryNext)
9372         continue;
9373
9374       // Check for #2
9375       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
9376         SDValue Result = isLoad
9377           ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9378                                BasePtr, Offset, AM)
9379           : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9380                                 BasePtr, Offset, AM);
9381         ++PostIndexedNodes;
9382         ++NodesCombined;
9383         DEBUG(dbgs() << "\nReplacing.5 ";
9384               N->dump(&DAG);
9385               dbgs() << "\nWith: ";
9386               Result.getNode()->dump(&DAG);
9387               dbgs() << '\n');
9388         WorklistRemover DeadNodes(*this);
9389         if (isLoad) {
9390           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9391           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9392         } else {
9393           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9394         }
9395
9396         // Finally, since the node is now dead, remove it from the graph.
9397         deleteAndRecombine(N);
9398
9399         // Replace the uses of Use with uses of the updated base value.
9400         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
9401                                       Result.getValue(isLoad ? 1 : 0));
9402         deleteAndRecombine(Op);
9403         return true;
9404       }
9405     }
9406   }
9407
9408   return false;
9409 }
9410
9411 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
9412 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
9413   ISD::MemIndexedMode AM = LD->getAddressingMode();
9414   assert(AM != ISD::UNINDEXED);
9415   SDValue BP = LD->getOperand(1);
9416   SDValue Inc = LD->getOperand(2);
9417
9418   // Some backends use TargetConstants for load offsets, but don't expect
9419   // TargetConstants in general ADD nodes. We can convert these constants into
9420   // regular Constants (if the constant is not opaque).
9421   assert((Inc.getOpcode() != ISD::TargetConstant ||
9422           !cast<ConstantSDNode>(Inc)->isOpaque()) &&
9423          "Cannot split out indexing using opaque target constants");
9424   if (Inc.getOpcode() == ISD::TargetConstant) {
9425     ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
9426     Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc),
9427                           ConstInc->getValueType(0));
9428   }
9429
9430   unsigned Opc =
9431       (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
9432   return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
9433 }
9434
9435 SDValue DAGCombiner::visitLOAD(SDNode *N) {
9436   LoadSDNode *LD  = cast<LoadSDNode>(N);
9437   SDValue Chain = LD->getChain();
9438   SDValue Ptr   = LD->getBasePtr();
9439
9440   // If load is not volatile and there are no uses of the loaded value (and
9441   // the updated indexed value in case of indexed loads), change uses of the
9442   // chain value into uses of the chain input (i.e. delete the dead load).
9443   if (!LD->isVolatile()) {
9444     if (N->getValueType(1) == MVT::Other) {
9445       // Unindexed loads.
9446       if (!N->hasAnyUseOfValue(0)) {
9447         // It's not safe to use the two value CombineTo variant here. e.g.
9448         // v1, chain2 = load chain1, loc
9449         // v2, chain3 = load chain2, loc
9450         // v3         = add v2, c
9451         // Now we replace use of chain2 with chain1.  This makes the second load
9452         // isomorphic to the one we are deleting, and thus makes this load live.
9453         DEBUG(dbgs() << "\nReplacing.6 ";
9454               N->dump(&DAG);
9455               dbgs() << "\nWith chain: ";
9456               Chain.getNode()->dump(&DAG);
9457               dbgs() << "\n");
9458         WorklistRemover DeadNodes(*this);
9459         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
9460
9461         if (N->use_empty())
9462           deleteAndRecombine(N);
9463
9464         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
9465       }
9466     } else {
9467       // Indexed loads.
9468       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
9469
9470       // If this load has an opaque TargetConstant offset, then we cannot split
9471       // the indexing into an add/sub directly (that TargetConstant may not be
9472       // valid for a different type of node, and we cannot convert an opaque
9473       // target constant into a regular constant).
9474       bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
9475                        cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
9476
9477       if (!N->hasAnyUseOfValue(0) &&
9478           ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
9479         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
9480         SDValue Index;
9481         if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
9482           Index = SplitIndexingFromLoad(LD);
9483           // Try to fold the base pointer arithmetic into subsequent loads and
9484           // stores.
9485           AddUsersToWorklist(N);
9486         } else
9487           Index = DAG.getUNDEF(N->getValueType(1));
9488         DEBUG(dbgs() << "\nReplacing.7 ";
9489               N->dump(&DAG);
9490               dbgs() << "\nWith: ";
9491               Undef.getNode()->dump(&DAG);
9492               dbgs() << " and 2 other values\n");
9493         WorklistRemover DeadNodes(*this);
9494         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
9495         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
9496         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
9497         deleteAndRecombine(N);
9498         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
9499       }
9500     }
9501   }
9502
9503   // If this load is directly stored, replace the load value with the stored
9504   // value.
9505   // TODO: Handle store large -> read small portion.
9506   // TODO: Handle TRUNCSTORE/LOADEXT
9507   if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
9508     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
9509       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
9510       if (PrevST->getBasePtr() == Ptr &&
9511           PrevST->getValue().getValueType() == N->getValueType(0))
9512       return CombineTo(N, Chain.getOperand(1), Chain);
9513     }
9514   }
9515
9516   // Try to infer better alignment information than the load already has.
9517   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
9518     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9519       if (Align > LD->getMemOperand()->getBaseAlignment()) {
9520         SDValue NewLoad =
9521                DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
9522                               LD->getValueType(0),
9523                               Chain, Ptr, LD->getPointerInfo(),
9524                               LD->getMemoryVT(),
9525                               LD->isVolatile(), LD->isNonTemporal(),
9526                               LD->isInvariant(), Align, LD->getAAInfo());
9527         if (NewLoad.getNode() != N)
9528           return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
9529       }
9530     }
9531   }
9532
9533   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
9534                                                   : DAG.getSubtarget().useAA();
9535 #ifndef NDEBUG
9536   if (CombinerAAOnlyFunc.getNumOccurrences() &&
9537       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9538     UseAA = false;
9539 #endif
9540   if (UseAA && LD->isUnindexed()) {
9541     // Walk up chain skipping non-aliasing memory nodes.
9542     SDValue BetterChain = FindBetterChain(N, Chain);
9543
9544     // If there is a better chain.
9545     if (Chain != BetterChain) {
9546       SDValue ReplLoad;
9547
9548       // Replace the chain to void dependency.
9549       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
9550         ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
9551                                BetterChain, Ptr, LD->getMemOperand());
9552       } else {
9553         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
9554                                   LD->getValueType(0),
9555                                   BetterChain, Ptr, LD->getMemoryVT(),
9556                                   LD->getMemOperand());
9557       }
9558
9559       // Create token factor to keep old chain connected.
9560       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9561                                   MVT::Other, Chain, ReplLoad.getValue(1));
9562
9563       // Make sure the new and old chains are cleaned up.
9564       AddToWorklist(Token.getNode());
9565
9566       // Replace uses with load result and token factor. Don't add users
9567       // to work list.
9568       return CombineTo(N, ReplLoad.getValue(0), Token, false);
9569     }
9570   }
9571
9572   // Try transforming N to an indexed load.
9573   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9574     return SDValue(N, 0);
9575
9576   // Try to slice up N to more direct loads if the slices are mapped to
9577   // different register banks or pairing can take place.
9578   if (SliceUpLoad(N))
9579     return SDValue(N, 0);
9580
9581   return SDValue();
9582 }
9583
9584 namespace {
9585 /// \brief Helper structure used to slice a load in smaller loads.
9586 /// Basically a slice is obtained from the following sequence:
9587 /// Origin = load Ty1, Base
9588 /// Shift = srl Ty1 Origin, CstTy Amount
9589 /// Inst = trunc Shift to Ty2
9590 ///
9591 /// Then, it will be rewriten into:
9592 /// Slice = load SliceTy, Base + SliceOffset
9593 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
9594 ///
9595 /// SliceTy is deduced from the number of bits that are actually used to
9596 /// build Inst.
9597 struct LoadedSlice {
9598   /// \brief Helper structure used to compute the cost of a slice.
9599   struct Cost {
9600     /// Are we optimizing for code size.
9601     bool ForCodeSize;
9602     /// Various cost.
9603     unsigned Loads;
9604     unsigned Truncates;
9605     unsigned CrossRegisterBanksCopies;
9606     unsigned ZExts;
9607     unsigned Shift;
9608
9609     Cost(bool ForCodeSize = false)
9610         : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
9611           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
9612
9613     /// \brief Get the cost of one isolated slice.
9614     Cost(const LoadedSlice &LS, bool ForCodeSize = false)
9615         : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
9616           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
9617       EVT TruncType = LS.Inst->getValueType(0);
9618       EVT LoadedType = LS.getLoadedType();
9619       if (TruncType != LoadedType &&
9620           !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
9621         ZExts = 1;
9622     }
9623
9624     /// \brief Account for slicing gain in the current cost.
9625     /// Slicing provide a few gains like removing a shift or a
9626     /// truncate. This method allows to grow the cost of the original
9627     /// load with the gain from this slice.
9628     void addSliceGain(const LoadedSlice &LS) {
9629       // Each slice saves a truncate.
9630       const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
9631       if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
9632                               LS.Inst->getOperand(0).getValueType()))
9633         ++Truncates;
9634       // If there is a shift amount, this slice gets rid of it.
9635       if (LS.Shift)
9636         ++Shift;
9637       // If this slice can merge a cross register bank copy, account for it.
9638       if (LS.canMergeExpensiveCrossRegisterBankCopy())
9639         ++CrossRegisterBanksCopies;
9640     }
9641
9642     Cost &operator+=(const Cost &RHS) {
9643       Loads += RHS.Loads;
9644       Truncates += RHS.Truncates;
9645       CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
9646       ZExts += RHS.ZExts;
9647       Shift += RHS.Shift;
9648       return *this;
9649     }
9650
9651     bool operator==(const Cost &RHS) const {
9652       return Loads == RHS.Loads && Truncates == RHS.Truncates &&
9653              CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
9654              ZExts == RHS.ZExts && Shift == RHS.Shift;
9655     }
9656
9657     bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
9658
9659     bool operator<(const Cost &RHS) const {
9660       // Assume cross register banks copies are as expensive as loads.
9661       // FIXME: Do we want some more target hooks?
9662       unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
9663       unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
9664       // Unless we are optimizing for code size, consider the
9665       // expensive operation first.
9666       if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
9667         return ExpensiveOpsLHS < ExpensiveOpsRHS;
9668       return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
9669              (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
9670     }
9671
9672     bool operator>(const Cost &RHS) const { return RHS < *this; }
9673
9674     bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
9675
9676     bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
9677   };
9678   // The last instruction that represent the slice. This should be a
9679   // truncate instruction.
9680   SDNode *Inst;
9681   // The original load instruction.
9682   LoadSDNode *Origin;
9683   // The right shift amount in bits from the original load.
9684   unsigned Shift;
9685   // The DAG from which Origin came from.
9686   // This is used to get some contextual information about legal types, etc.
9687   SelectionDAG *DAG;
9688
9689   LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
9690               unsigned Shift = 0, SelectionDAG *DAG = nullptr)
9691       : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
9692
9693   /// \brief Get the bits used in a chunk of bits \p BitWidth large.
9694   /// \return Result is \p BitWidth and has used bits set to 1 and
9695   ///         not used bits set to 0.
9696   APInt getUsedBits() const {
9697     // Reproduce the trunc(lshr) sequence:
9698     // - Start from the truncated value.
9699     // - Zero extend to the desired bit width.
9700     // - Shift left.
9701     assert(Origin && "No original load to compare against.");
9702     unsigned BitWidth = Origin->getValueSizeInBits(0);
9703     assert(Inst && "This slice is not bound to an instruction");
9704     assert(Inst->getValueSizeInBits(0) <= BitWidth &&
9705            "Extracted slice is bigger than the whole type!");
9706     APInt UsedBits(Inst->getValueSizeInBits(0), 0);
9707     UsedBits.setAllBits();
9708     UsedBits = UsedBits.zext(BitWidth);
9709     UsedBits <<= Shift;
9710     return UsedBits;
9711   }
9712
9713   /// \brief Get the size of the slice to be loaded in bytes.
9714   unsigned getLoadedSize() const {
9715     unsigned SliceSize = getUsedBits().countPopulation();
9716     assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
9717     return SliceSize / 8;
9718   }
9719
9720   /// \brief Get the type that will be loaded for this slice.
9721   /// Note: This may not be the final type for the slice.
9722   EVT getLoadedType() const {
9723     assert(DAG && "Missing context");
9724     LLVMContext &Ctxt = *DAG->getContext();
9725     return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
9726   }
9727
9728   /// \brief Get the alignment of the load used for this slice.
9729   unsigned getAlignment() const {
9730     unsigned Alignment = Origin->getAlignment();
9731     unsigned Offset = getOffsetFromBase();
9732     if (Offset != 0)
9733       Alignment = MinAlign(Alignment, Alignment + Offset);
9734     return Alignment;
9735   }
9736
9737   /// \brief Check if this slice can be rewritten with legal operations.
9738   bool isLegal() const {
9739     // An invalid slice is not legal.
9740     if (!Origin || !Inst || !DAG)
9741       return false;
9742
9743     // Offsets are for indexed load only, we do not handle that.
9744     if (Origin->getOffset().getOpcode() != ISD::UNDEF)
9745       return false;
9746
9747     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
9748
9749     // Check that the type is legal.
9750     EVT SliceType = getLoadedType();
9751     if (!TLI.isTypeLegal(SliceType))
9752       return false;
9753
9754     // Check that the load is legal for this type.
9755     if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
9756       return false;
9757
9758     // Check that the offset can be computed.
9759     // 1. Check its type.
9760     EVT PtrType = Origin->getBasePtr().getValueType();
9761     if (PtrType == MVT::Untyped || PtrType.isExtended())
9762       return false;
9763
9764     // 2. Check that it fits in the immediate.
9765     if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
9766       return false;
9767
9768     // 3. Check that the computation is legal.
9769     if (!TLI.isOperationLegal(ISD::ADD, PtrType))
9770       return false;
9771
9772     // Check that the zext is legal if it needs one.
9773     EVT TruncateType = Inst->getValueType(0);
9774     if (TruncateType != SliceType &&
9775         !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
9776       return false;
9777
9778     return true;
9779   }
9780
9781   /// \brief Get the offset in bytes of this slice in the original chunk of
9782   /// bits.
9783   /// \pre DAG != nullptr.
9784   uint64_t getOffsetFromBase() const {
9785     assert(DAG && "Missing context.");
9786     bool IsBigEndian =
9787         DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
9788     assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
9789     uint64_t Offset = Shift / 8;
9790     unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
9791     assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
9792            "The size of the original loaded type is not a multiple of a"
9793            " byte.");
9794     // If Offset is bigger than TySizeInBytes, it means we are loading all
9795     // zeros. This should have been optimized before in the process.
9796     assert(TySizeInBytes > Offset &&
9797            "Invalid shift amount for given loaded size");
9798     if (IsBigEndian)
9799       Offset = TySizeInBytes - Offset - getLoadedSize();
9800     return Offset;
9801   }
9802
9803   /// \brief Generate the sequence of instructions to load the slice
9804   /// represented by this object and redirect the uses of this slice to
9805   /// this new sequence of instructions.
9806   /// \pre this->Inst && this->Origin are valid Instructions and this
9807   /// object passed the legal check: LoadedSlice::isLegal returned true.
9808   /// \return The last instruction of the sequence used to load the slice.
9809   SDValue loadSlice() const {
9810     assert(Inst && Origin && "Unable to replace a non-existing slice.");
9811     const SDValue &OldBaseAddr = Origin->getBasePtr();
9812     SDValue BaseAddr = OldBaseAddr;
9813     // Get the offset in that chunk of bytes w.r.t. the endianess.
9814     int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
9815     assert(Offset >= 0 && "Offset too big to fit in int64_t!");
9816     if (Offset) {
9817       // BaseAddr = BaseAddr + Offset.
9818       EVT ArithType = BaseAddr.getValueType();
9819       SDLoc DL(Origin);
9820       BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr,
9821                               DAG->getConstant(Offset, DL, ArithType));
9822     }
9823
9824     // Create the type of the loaded slice according to its size.
9825     EVT SliceType = getLoadedType();
9826
9827     // Create the load for the slice.
9828     SDValue LastInst = DAG->getLoad(
9829         SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
9830         Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
9831         Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
9832     // If the final type is not the same as the loaded type, this means that
9833     // we have to pad with zero. Create a zero extend for that.
9834     EVT FinalType = Inst->getValueType(0);
9835     if (SliceType != FinalType)
9836       LastInst =
9837           DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
9838     return LastInst;
9839   }
9840
9841   /// \brief Check if this slice can be merged with an expensive cross register
9842   /// bank copy. E.g.,
9843   /// i = load i32
9844   /// f = bitcast i32 i to float
9845   bool canMergeExpensiveCrossRegisterBankCopy() const {
9846     if (!Inst || !Inst->hasOneUse())
9847       return false;
9848     SDNode *Use = *Inst->use_begin();
9849     if (Use->getOpcode() != ISD::BITCAST)
9850       return false;
9851     assert(DAG && "Missing context");
9852     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
9853     EVT ResVT = Use->getValueType(0);
9854     const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
9855     const TargetRegisterClass *ArgRC =
9856         TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
9857     if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
9858       return false;
9859
9860     // At this point, we know that we perform a cross-register-bank copy.
9861     // Check if it is expensive.
9862     const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
9863     // Assume bitcasts are cheap, unless both register classes do not
9864     // explicitly share a common sub class.
9865     if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
9866       return false;
9867
9868     // Check if it will be merged with the load.
9869     // 1. Check the alignment constraint.
9870     unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
9871         ResVT.getTypeForEVT(*DAG->getContext()));
9872
9873     if (RequiredAlignment > getAlignment())
9874       return false;
9875
9876     // 2. Check that the load is a legal operation for that type.
9877     if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
9878       return false;
9879
9880     // 3. Check that we do not have a zext in the way.
9881     if (Inst->getValueType(0) != getLoadedType())
9882       return false;
9883
9884     return true;
9885   }
9886 };
9887 }
9888
9889 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
9890 /// \p UsedBits looks like 0..0 1..1 0..0.
9891 static bool areUsedBitsDense(const APInt &UsedBits) {
9892   // If all the bits are one, this is dense!
9893   if (UsedBits.isAllOnesValue())
9894     return true;
9895
9896   // Get rid of the unused bits on the right.
9897   APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
9898   // Get rid of the unused bits on the left.
9899   if (NarrowedUsedBits.countLeadingZeros())
9900     NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
9901   // Check that the chunk of bits is completely used.
9902   return NarrowedUsedBits.isAllOnesValue();
9903 }
9904
9905 /// \brief Check whether or not \p First and \p Second are next to each other
9906 /// in memory. This means that there is no hole between the bits loaded
9907 /// by \p First and the bits loaded by \p Second.
9908 static bool areSlicesNextToEachOther(const LoadedSlice &First,
9909                                      const LoadedSlice &Second) {
9910   assert(First.Origin == Second.Origin && First.Origin &&
9911          "Unable to match different memory origins.");
9912   APInt UsedBits = First.getUsedBits();
9913   assert((UsedBits & Second.getUsedBits()) == 0 &&
9914          "Slices are not supposed to overlap.");
9915   UsedBits |= Second.getUsedBits();
9916   return areUsedBitsDense(UsedBits);
9917 }
9918
9919 /// \brief Adjust the \p GlobalLSCost according to the target
9920 /// paring capabilities and the layout of the slices.
9921 /// \pre \p GlobalLSCost should account for at least as many loads as
9922 /// there is in the slices in \p LoadedSlices.
9923 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
9924                                  LoadedSlice::Cost &GlobalLSCost) {
9925   unsigned NumberOfSlices = LoadedSlices.size();
9926   // If there is less than 2 elements, no pairing is possible.
9927   if (NumberOfSlices < 2)
9928     return;
9929
9930   // Sort the slices so that elements that are likely to be next to each
9931   // other in memory are next to each other in the list.
9932   std::sort(LoadedSlices.begin(), LoadedSlices.end(),
9933             [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
9934     assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
9935     return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
9936   });
9937   const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
9938   // First (resp. Second) is the first (resp. Second) potentially candidate
9939   // to be placed in a paired load.
9940   const LoadedSlice *First = nullptr;
9941   const LoadedSlice *Second = nullptr;
9942   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
9943                 // Set the beginning of the pair.
9944                                                            First = Second) {
9945
9946     Second = &LoadedSlices[CurrSlice];
9947
9948     // If First is NULL, it means we start a new pair.
9949     // Get to the next slice.
9950     if (!First)
9951       continue;
9952
9953     EVT LoadedType = First->getLoadedType();
9954
9955     // If the types of the slices are different, we cannot pair them.
9956     if (LoadedType != Second->getLoadedType())
9957       continue;
9958
9959     // Check if the target supplies paired loads for this type.
9960     unsigned RequiredAlignment = 0;
9961     if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
9962       // move to the next pair, this type is hopeless.
9963       Second = nullptr;
9964       continue;
9965     }
9966     // Check if we meet the alignment requirement.
9967     if (RequiredAlignment > First->getAlignment())
9968       continue;
9969
9970     // Check that both loads are next to each other in memory.
9971     if (!areSlicesNextToEachOther(*First, *Second))
9972       continue;
9973
9974     assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
9975     --GlobalLSCost.Loads;
9976     // Move to the next pair.
9977     Second = nullptr;
9978   }
9979 }
9980
9981 /// \brief Check the profitability of all involved LoadedSlice.
9982 /// Currently, it is considered profitable if there is exactly two
9983 /// involved slices (1) which are (2) next to each other in memory, and
9984 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
9985 ///
9986 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
9987 /// the elements themselves.
9988 ///
9989 /// FIXME: When the cost model will be mature enough, we can relax
9990 /// constraints (1) and (2).
9991 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
9992                                 const APInt &UsedBits, bool ForCodeSize) {
9993   unsigned NumberOfSlices = LoadedSlices.size();
9994   if (StressLoadSlicing)
9995     return NumberOfSlices > 1;
9996
9997   // Check (1).
9998   if (NumberOfSlices != 2)
9999     return false;
10000
10001   // Check (2).
10002   if (!areUsedBitsDense(UsedBits))
10003     return false;
10004
10005   // Check (3).
10006   LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
10007   // The original code has one big load.
10008   OrigCost.Loads = 1;
10009   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
10010     const LoadedSlice &LS = LoadedSlices[CurrSlice];
10011     // Accumulate the cost of all the slices.
10012     LoadedSlice::Cost SliceCost(LS, ForCodeSize);
10013     GlobalSlicingCost += SliceCost;
10014
10015     // Account as cost in the original configuration the gain obtained
10016     // with the current slices.
10017     OrigCost.addSliceGain(LS);
10018   }
10019
10020   // If the target supports paired load, adjust the cost accordingly.
10021   adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
10022   return OrigCost > GlobalSlicingCost;
10023 }
10024
10025 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
10026 /// operations, split it in the various pieces being extracted.
10027 ///
10028 /// This sort of thing is introduced by SROA.
10029 /// This slicing takes care not to insert overlapping loads.
10030 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
10031 bool DAGCombiner::SliceUpLoad(SDNode *N) {
10032   if (Level < AfterLegalizeDAG)
10033     return false;
10034
10035   LoadSDNode *LD = cast<LoadSDNode>(N);
10036   if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
10037       !LD->getValueType(0).isInteger())
10038     return false;
10039
10040   // Keep track of already used bits to detect overlapping values.
10041   // In that case, we will just abort the transformation.
10042   APInt UsedBits(LD->getValueSizeInBits(0), 0);
10043
10044   SmallVector<LoadedSlice, 4> LoadedSlices;
10045
10046   // Check if this load is used as several smaller chunks of bits.
10047   // Basically, look for uses in trunc or trunc(lshr) and record a new chain
10048   // of computation for each trunc.
10049   for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
10050        UI != UIEnd; ++UI) {
10051     // Skip the uses of the chain.
10052     if (UI.getUse().getResNo() != 0)
10053       continue;
10054
10055     SDNode *User = *UI;
10056     unsigned Shift = 0;
10057
10058     // Check if this is a trunc(lshr).
10059     if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
10060         isa<ConstantSDNode>(User->getOperand(1))) {
10061       Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
10062       User = *User->use_begin();
10063     }
10064
10065     // At this point, User is a Truncate, iff we encountered, trunc or
10066     // trunc(lshr).
10067     if (User->getOpcode() != ISD::TRUNCATE)
10068       return false;
10069
10070     // The width of the type must be a power of 2 and greater than 8-bits.
10071     // Otherwise the load cannot be represented in LLVM IR.
10072     // Moreover, if we shifted with a non-8-bits multiple, the slice
10073     // will be across several bytes. We do not support that.
10074     unsigned Width = User->getValueSizeInBits(0);
10075     if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
10076       return 0;
10077
10078     // Build the slice for this chain of computations.
10079     LoadedSlice LS(User, LD, Shift, &DAG);
10080     APInt CurrentUsedBits = LS.getUsedBits();
10081
10082     // Check if this slice overlaps with another.
10083     if ((CurrentUsedBits & UsedBits) != 0)
10084       return false;
10085     // Update the bits used globally.
10086     UsedBits |= CurrentUsedBits;
10087
10088     // Check if the new slice would be legal.
10089     if (!LS.isLegal())
10090       return false;
10091
10092     // Record the slice.
10093     LoadedSlices.push_back(LS);
10094   }
10095
10096   // Abort slicing if it does not seem to be profitable.
10097   if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
10098     return false;
10099
10100   ++SlicedLoads;
10101
10102   // Rewrite each chain to use an independent load.
10103   // By construction, each chain can be represented by a unique load.
10104
10105   // Prepare the argument for the new token factor for all the slices.
10106   SmallVector<SDValue, 8> ArgChains;
10107   for (SmallVectorImpl<LoadedSlice>::const_iterator
10108            LSIt = LoadedSlices.begin(),
10109            LSItEnd = LoadedSlices.end();
10110        LSIt != LSItEnd; ++LSIt) {
10111     SDValue SliceInst = LSIt->loadSlice();
10112     CombineTo(LSIt->Inst, SliceInst, true);
10113     if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
10114       SliceInst = SliceInst.getOperand(0);
10115     assert(SliceInst->getOpcode() == ISD::LOAD &&
10116            "It takes more than a zext to get to the loaded slice!!");
10117     ArgChains.push_back(SliceInst.getValue(1));
10118   }
10119
10120   SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
10121                               ArgChains);
10122   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
10123   return true;
10124 }
10125
10126 /// Check to see if V is (and load (ptr), imm), where the load is having
10127 /// specific bytes cleared out.  If so, return the byte size being masked out
10128 /// and the shift amount.
10129 static std::pair<unsigned, unsigned>
10130 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
10131   std::pair<unsigned, unsigned> Result(0, 0);
10132
10133   // Check for the structure we're looking for.
10134   if (V->getOpcode() != ISD::AND ||
10135       !isa<ConstantSDNode>(V->getOperand(1)) ||
10136       !ISD::isNormalLoad(V->getOperand(0).getNode()))
10137     return Result;
10138
10139   // Check the chain and pointer.
10140   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
10141   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
10142
10143   // The store should be chained directly to the load or be an operand of a
10144   // tokenfactor.
10145   if (LD == Chain.getNode())
10146     ; // ok.
10147   else if (Chain->getOpcode() != ISD::TokenFactor)
10148     return Result; // Fail.
10149   else {
10150     bool isOk = false;
10151     for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
10152       if (Chain->getOperand(i).getNode() == LD) {
10153         isOk = true;
10154         break;
10155       }
10156     if (!isOk) return Result;
10157   }
10158
10159   // This only handles simple types.
10160   if (V.getValueType() != MVT::i16 &&
10161       V.getValueType() != MVT::i32 &&
10162       V.getValueType() != MVT::i64)
10163     return Result;
10164
10165   // Check the constant mask.  Invert it so that the bits being masked out are
10166   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
10167   // follow the sign bit for uniformity.
10168   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
10169   unsigned NotMaskLZ = countLeadingZeros(NotMask);
10170   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
10171   unsigned NotMaskTZ = countTrailingZeros(NotMask);
10172   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
10173   if (NotMaskLZ == 64) return Result;  // All zero mask.
10174
10175   // See if we have a continuous run of bits.  If so, we have 0*1+0*
10176   if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64)
10177     return Result;
10178
10179   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
10180   if (V.getValueType() != MVT::i64 && NotMaskLZ)
10181     NotMaskLZ -= 64-V.getValueSizeInBits();
10182
10183   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
10184   switch (MaskedBytes) {
10185   case 1:
10186   case 2:
10187   case 4: break;
10188   default: return Result; // All one mask, or 5-byte mask.
10189   }
10190
10191   // Verify that the first bit starts at a multiple of mask so that the access
10192   // is aligned the same as the access width.
10193   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
10194
10195   Result.first = MaskedBytes;
10196   Result.second = NotMaskTZ/8;
10197   return Result;
10198 }
10199
10200
10201 /// Check to see if IVal is something that provides a value as specified by
10202 /// MaskInfo. If so, replace the specified store with a narrower store of
10203 /// truncated IVal.
10204 static SDNode *
10205 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
10206                                 SDValue IVal, StoreSDNode *St,
10207                                 DAGCombiner *DC) {
10208   unsigned NumBytes = MaskInfo.first;
10209   unsigned ByteShift = MaskInfo.second;
10210   SelectionDAG &DAG = DC->getDAG();
10211
10212   // Check to see if IVal is all zeros in the part being masked in by the 'or'
10213   // that uses this.  If not, this is not a replacement.
10214   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
10215                                   ByteShift*8, (ByteShift+NumBytes)*8);
10216   if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
10217
10218   // Check that it is legal on the target to do this.  It is legal if the new
10219   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
10220   // legalization.
10221   MVT VT = MVT::getIntegerVT(NumBytes*8);
10222   if (!DC->isTypeLegal(VT))
10223     return nullptr;
10224
10225   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
10226   // shifted by ByteShift and truncated down to NumBytes.
10227   if (ByteShift) {
10228     SDLoc DL(IVal);
10229     IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal,
10230                        DAG.getConstant(ByteShift*8, DL,
10231                                     DC->getShiftAmountTy(IVal.getValueType())));
10232   }
10233
10234   // Figure out the offset for the store and the alignment of the access.
10235   unsigned StOffset;
10236   unsigned NewAlign = St->getAlignment();
10237
10238   if (DAG.getTargetLoweringInfo().isLittleEndian())
10239     StOffset = ByteShift;
10240   else
10241     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
10242
10243   SDValue Ptr = St->getBasePtr();
10244   if (StOffset) {
10245     SDLoc DL(IVal);
10246     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(),
10247                       Ptr, DAG.getConstant(StOffset, DL, Ptr.getValueType()));
10248     NewAlign = MinAlign(NewAlign, StOffset);
10249   }
10250
10251   // Truncate down to the new size.
10252   IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
10253
10254   ++OpsNarrowed;
10255   return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
10256                       St->getPointerInfo().getWithOffset(StOffset),
10257                       false, false, NewAlign).getNode();
10258 }
10259
10260
10261 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
10262 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
10263 /// narrowing the load and store if it would end up being a win for performance
10264 /// or code size.
10265 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
10266   StoreSDNode *ST  = cast<StoreSDNode>(N);
10267   if (ST->isVolatile())
10268     return SDValue();
10269
10270   SDValue Chain = ST->getChain();
10271   SDValue Value = ST->getValue();
10272   SDValue Ptr   = ST->getBasePtr();
10273   EVT VT = Value.getValueType();
10274
10275   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
10276     return SDValue();
10277
10278   unsigned Opc = Value.getOpcode();
10279
10280   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
10281   // is a byte mask indicating a consecutive number of bytes, check to see if
10282   // Y is known to provide just those bytes.  If so, we try to replace the
10283   // load + replace + store sequence with a single (narrower) store, which makes
10284   // the load dead.
10285   if (Opc == ISD::OR) {
10286     std::pair<unsigned, unsigned> MaskedLoad;
10287     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
10288     if (MaskedLoad.first)
10289       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10290                                                   Value.getOperand(1), ST,this))
10291         return SDValue(NewST, 0);
10292
10293     // Or is commutative, so try swapping X and Y.
10294     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
10295     if (MaskedLoad.first)
10296       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10297                                                   Value.getOperand(0), ST,this))
10298         return SDValue(NewST, 0);
10299   }
10300
10301   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
10302       Value.getOperand(1).getOpcode() != ISD::Constant)
10303     return SDValue();
10304
10305   SDValue N0 = Value.getOperand(0);
10306   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
10307       Chain == SDValue(N0.getNode(), 1)) {
10308     LoadSDNode *LD = cast<LoadSDNode>(N0);
10309     if (LD->getBasePtr() != Ptr ||
10310         LD->getPointerInfo().getAddrSpace() !=
10311         ST->getPointerInfo().getAddrSpace())
10312       return SDValue();
10313
10314     // Find the type to narrow it the load / op / store to.
10315     SDValue N1 = Value.getOperand(1);
10316     unsigned BitWidth = N1.getValueSizeInBits();
10317     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
10318     if (Opc == ISD::AND)
10319       Imm ^= APInt::getAllOnesValue(BitWidth);
10320     if (Imm == 0 || Imm.isAllOnesValue())
10321       return SDValue();
10322     unsigned ShAmt = Imm.countTrailingZeros();
10323     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
10324     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
10325     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10326     // The narrowing should be profitable, the load/store operation should be
10327     // legal (or custom) and the store size should be equal to the NewVT width.
10328     while (NewBW < BitWidth &&
10329            (NewVT.getStoreSizeInBits() != NewBW ||
10330             !TLI.isOperationLegalOrCustom(Opc, NewVT) ||
10331             !TLI.isNarrowingProfitable(VT, NewVT))) {
10332       NewBW = NextPowerOf2(NewBW);
10333       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10334     }
10335     if (NewBW >= BitWidth)
10336       return SDValue();
10337
10338     // If the lsb changed does not start at the type bitwidth boundary,
10339     // start at the previous one.
10340     if (ShAmt % NewBW)
10341       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
10342     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
10343                                    std::min(BitWidth, ShAmt + NewBW));
10344     if ((Imm & Mask) == Imm) {
10345       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
10346       if (Opc == ISD::AND)
10347         NewImm ^= APInt::getAllOnesValue(NewBW);
10348       uint64_t PtrOff = ShAmt / 8;
10349       // For big endian targets, we need to adjust the offset to the pointer to
10350       // load the correct bytes.
10351       if (TLI.isBigEndian())
10352         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
10353
10354       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
10355       Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
10356       if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
10357         return SDValue();
10358
10359       SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
10360                                    Ptr.getValueType(), Ptr,
10361                                    DAG.getConstant(PtrOff, SDLoc(LD),
10362                                                    Ptr.getValueType()));
10363       SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
10364                                   LD->getChain(), NewPtr,
10365                                   LD->getPointerInfo().getWithOffset(PtrOff),
10366                                   LD->isVolatile(), LD->isNonTemporal(),
10367                                   LD->isInvariant(), NewAlign,
10368                                   LD->getAAInfo());
10369       SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
10370                                    DAG.getConstant(NewImm, SDLoc(Value),
10371                                                    NewVT));
10372       SDValue NewST = DAG.getStore(Chain, SDLoc(N),
10373                                    NewVal, NewPtr,
10374                                    ST->getPointerInfo().getWithOffset(PtrOff),
10375                                    false, false, NewAlign);
10376
10377       AddToWorklist(NewPtr.getNode());
10378       AddToWorklist(NewLD.getNode());
10379       AddToWorklist(NewVal.getNode());
10380       WorklistRemover DeadNodes(*this);
10381       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
10382       ++OpsNarrowed;
10383       return NewST;
10384     }
10385   }
10386
10387   return SDValue();
10388 }
10389
10390 /// For a given floating point load / store pair, if the load value isn't used
10391 /// by any other operations, then consider transforming the pair to integer
10392 /// load / store operations if the target deems the transformation profitable.
10393 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
10394   StoreSDNode *ST  = cast<StoreSDNode>(N);
10395   SDValue Chain = ST->getChain();
10396   SDValue Value = ST->getValue();
10397   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
10398       Value.hasOneUse() &&
10399       Chain == SDValue(Value.getNode(), 1)) {
10400     LoadSDNode *LD = cast<LoadSDNode>(Value);
10401     EVT VT = LD->getMemoryVT();
10402     if (!VT.isFloatingPoint() ||
10403         VT != ST->getMemoryVT() ||
10404         LD->isNonTemporal() ||
10405         ST->isNonTemporal() ||
10406         LD->getPointerInfo().getAddrSpace() != 0 ||
10407         ST->getPointerInfo().getAddrSpace() != 0)
10408       return SDValue();
10409
10410     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
10411     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
10412         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
10413         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
10414         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
10415       return SDValue();
10416
10417     unsigned LDAlign = LD->getAlignment();
10418     unsigned STAlign = ST->getAlignment();
10419     Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
10420     unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
10421     if (LDAlign < ABIAlign || STAlign < ABIAlign)
10422       return SDValue();
10423
10424     SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
10425                                 LD->getChain(), LD->getBasePtr(),
10426                                 LD->getPointerInfo(),
10427                                 false, false, false, LDAlign);
10428
10429     SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
10430                                  NewLD, ST->getBasePtr(),
10431                                  ST->getPointerInfo(),
10432                                  false, false, STAlign);
10433
10434     AddToWorklist(NewLD.getNode());
10435     AddToWorklist(NewST.getNode());
10436     WorklistRemover DeadNodes(*this);
10437     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
10438     ++LdStFP2Int;
10439     return NewST;
10440   }
10441
10442   return SDValue();
10443 }
10444
10445 namespace {
10446 /// Helper struct to parse and store a memory address as base + index + offset.
10447 /// We ignore sign extensions when it is safe to do so.
10448 /// The following two expressions are not equivalent. To differentiate we need
10449 /// to store whether there was a sign extension involved in the index
10450 /// computation.
10451 ///  (load (i64 add (i64 copyfromreg %c)
10452 ///                 (i64 signextend (add (i8 load %index)
10453 ///                                      (i8 1))))
10454 /// vs
10455 ///
10456 /// (load (i64 add (i64 copyfromreg %c)
10457 ///                (i64 signextend (i32 add (i32 signextend (i8 load %index))
10458 ///                                         (i32 1)))))
10459 struct BaseIndexOffset {
10460   SDValue Base;
10461   SDValue Index;
10462   int64_t Offset;
10463   bool IsIndexSignExt;
10464
10465   BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
10466
10467   BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
10468                   bool IsIndexSignExt) :
10469     Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
10470
10471   bool equalBaseIndex(const BaseIndexOffset &Other) {
10472     return Other.Base == Base && Other.Index == Index &&
10473       Other.IsIndexSignExt == IsIndexSignExt;
10474   }
10475
10476   /// Parses tree in Ptr for base, index, offset addresses.
10477   static BaseIndexOffset match(SDValue Ptr) {
10478     bool IsIndexSignExt = false;
10479
10480     // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
10481     // instruction, then it could be just the BASE or everything else we don't
10482     // know how to handle. Just use Ptr as BASE and give up.
10483     if (Ptr->getOpcode() != ISD::ADD)
10484       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10485
10486     // We know that we have at least an ADD instruction. Try to pattern match
10487     // the simple case of BASE + OFFSET.
10488     if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
10489       int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
10490       return  BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
10491                               IsIndexSignExt);
10492     }
10493
10494     // Inside a loop the current BASE pointer is calculated using an ADD and a
10495     // MUL instruction. In this case Ptr is the actual BASE pointer.
10496     // (i64 add (i64 %array_ptr)
10497     //          (i64 mul (i64 %induction_var)
10498     //                   (i64 %element_size)))
10499     if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
10500       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10501
10502     // Look at Base + Index + Offset cases.
10503     SDValue Base = Ptr->getOperand(0);
10504     SDValue IndexOffset = Ptr->getOperand(1);
10505
10506     // Skip signextends.
10507     if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
10508       IndexOffset = IndexOffset->getOperand(0);
10509       IsIndexSignExt = true;
10510     }
10511
10512     // Either the case of Base + Index (no offset) or something else.
10513     if (IndexOffset->getOpcode() != ISD::ADD)
10514       return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
10515
10516     // Now we have the case of Base + Index + offset.
10517     SDValue Index = IndexOffset->getOperand(0);
10518     SDValue Offset = IndexOffset->getOperand(1);
10519
10520     if (!isa<ConstantSDNode>(Offset))
10521       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10522
10523     // Ignore signextends.
10524     if (Index->getOpcode() == ISD::SIGN_EXTEND) {
10525       Index = Index->getOperand(0);
10526       IsIndexSignExt = true;
10527     } else IsIndexSignExt = false;
10528
10529     int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
10530     return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
10531   }
10532 };
10533 } // namespace
10534
10535 bool DAGCombiner::MergeStoresOfConstantsOrVecElts(
10536                   SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT,
10537                   unsigned NumElem, bool IsConstantSrc, bool UseVector) {
10538   // Make sure we have something to merge.
10539   if (NumElem < 2)
10540     return false;
10541
10542   int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
10543   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
10544   unsigned LatestNodeUsed = 0;
10545
10546   for (unsigned i=0; i < NumElem; ++i) {
10547     // Find a chain for the new wide-store operand. Notice that some
10548     // of the store nodes that we found may not be selected for inclusion
10549     // in the wide store. The chain we use needs to be the chain of the
10550     // latest store node which is *used* and replaced by the wide store.
10551     if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
10552       LatestNodeUsed = i;
10553   }
10554
10555   // The latest Node in the DAG.
10556   LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
10557   SDLoc DL(StoreNodes[0].MemNode);
10558
10559   SDValue StoredVal;
10560   if (UseVector) {
10561     // Find a legal type for the vector store.
10562     EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
10563     assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
10564     if (IsConstantSrc) {
10565       // A vector store with a constant source implies that the constant is
10566       // zero; we only handle merging stores of constant zeros because the zero
10567       // can be materialized without a load.
10568       // It may be beneficial to loosen this restriction to allow non-zero
10569       // store merging.
10570       StoredVal = DAG.getConstant(0, DL, Ty);
10571     } else {
10572       SmallVector<SDValue, 8> Ops;
10573       for (unsigned i = 0; i < NumElem ; ++i) {
10574         StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10575         SDValue Val = St->getValue();
10576         // All of the operands of a BUILD_VECTOR must have the same type.
10577         if (Val.getValueType() != MemVT)
10578           return false;
10579         Ops.push_back(Val);
10580       }
10581
10582       // Build the extracted vector elements back into a vector.
10583       StoredVal = DAG.getNode(ISD::BUILD_VECTOR, DL, Ty, Ops);
10584     }
10585   } else {
10586     // We should always use a vector store when merging extracted vector
10587     // elements, so this path implies a store of constants.
10588     assert(IsConstantSrc && "Merged vector elements should use vector store");
10589
10590     unsigned StoreBW = NumElem * ElementSizeBytes * 8;
10591     APInt StoreInt(StoreBW, 0);
10592
10593     // Construct a single integer constant which is made of the smaller
10594     // constant inputs.
10595     bool IsLE = TLI.isLittleEndian();
10596     for (unsigned i = 0; i < NumElem ; ++i) {
10597       unsigned Idx = IsLE ? (NumElem - 1 - i) : i;
10598       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
10599       SDValue Val = St->getValue();
10600       StoreInt <<= ElementSizeBytes*8;
10601       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
10602         StoreInt |= C->getAPIntValue().zext(StoreBW);
10603       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
10604         StoreInt |= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
10605       } else {
10606         llvm_unreachable("Invalid constant element type");
10607       }
10608     }
10609
10610     // Create the new Load and Store operations.
10611     EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10612     StoredVal = DAG.getConstant(StoreInt, DL, StoreTy);
10613   }
10614
10615   SDValue NewStore = DAG.getStore(LatestOp->getChain(), DL, StoredVal,
10616                                   FirstInChain->getBasePtr(),
10617                                   FirstInChain->getPointerInfo(),
10618                                   false, false,
10619                                   FirstInChain->getAlignment());
10620
10621   // Replace the last store with the new store
10622   CombineTo(LatestOp, NewStore);
10623   // Erase all other stores.
10624   for (unsigned i = 0; i < NumElem ; ++i) {
10625     if (StoreNodes[i].MemNode == LatestOp)
10626       continue;
10627     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10628     // ReplaceAllUsesWith will replace all uses that existed when it was
10629     // called, but graph optimizations may cause new ones to appear. For
10630     // example, the case in pr14333 looks like
10631     //
10632     //  St's chain -> St -> another store -> X
10633     //
10634     // And the only difference from St to the other store is the chain.
10635     // When we change it's chain to be St's chain they become identical,
10636     // get CSEed and the net result is that X is now a use of St.
10637     // Since we know that St is redundant, just iterate.
10638     while (!St->use_empty())
10639       DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
10640     deleteAndRecombine(St);
10641   }
10642
10643   return true;
10644 }
10645
10646 static bool allowableAlignment(const SelectionDAG &DAG,
10647                                const TargetLowering &TLI, EVT EVTTy,
10648                                unsigned AS, unsigned Align) {
10649   if (TLI.allowsMisalignedMemoryAccesses(EVTTy, AS, Align))
10650     return true;
10651
10652   Type *Ty = EVTTy.getTypeForEVT(*DAG.getContext());
10653   unsigned ABIAlignment = TLI.getDataLayout()->getPrefTypeAlignment(Ty);
10654   return (Align >= ABIAlignment);
10655 }
10656
10657 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
10658   if (OptLevel == CodeGenOpt::None)
10659     return false;
10660
10661   EVT MemVT = St->getMemoryVT();
10662   int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
10663   bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute(
10664       Attribute::NoImplicitFloat);
10665
10666   // This function cannot currently deal with non-byte-sized memory sizes.
10667   if (ElementSizeBytes * 8 != MemVT.getSizeInBits())
10668     return false;
10669
10670   // Don't merge vectors into wider inputs.
10671   if (MemVT.isVector() || !MemVT.isSimple())
10672     return false;
10673
10674   // Perform an early exit check. Do not bother looking at stored values that
10675   // are not constants, loads, or extracted vector elements.
10676   SDValue StoredVal = St->getValue();
10677   bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
10678   bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) ||
10679                        isa<ConstantFPSDNode>(StoredVal);
10680   bool IsExtractVecEltSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT);
10681
10682   if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecEltSrc)
10683     return false;
10684
10685   // Only look at ends of store sequences.
10686   SDValue Chain = SDValue(St, 0);
10687   if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
10688     return false;
10689
10690   // This holds the base pointer, index, and the offset in bytes from the base
10691   // pointer.
10692   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
10693
10694   // We must have a base and an offset.
10695   if (!BasePtr.Base.getNode())
10696     return false;
10697
10698   // Do not handle stores to undef base pointers.
10699   if (BasePtr.Base.getOpcode() == ISD::UNDEF)
10700     return false;
10701
10702   // Save the LoadSDNodes that we find in the chain.
10703   // We need to make sure that these nodes do not interfere with
10704   // any of the store nodes.
10705   SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
10706
10707   // Save the StoreSDNodes that we find in the chain.
10708   SmallVector<MemOpLink, 8> StoreNodes;
10709
10710   // Walk up the chain and look for nodes with offsets from the same
10711   // base pointer. Stop when reaching an instruction with a different kind
10712   // or instruction which has a different base pointer.
10713   unsigned Seq = 0;
10714   StoreSDNode *Index = St;
10715   while (Index) {
10716     // If the chain has more than one use, then we can't reorder the mem ops.
10717     if (Index != St && !SDValue(Index, 0)->hasOneUse())
10718       break;
10719
10720     // Find the base pointer and offset for this memory node.
10721     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
10722
10723     // Check that the base pointer is the same as the original one.
10724     if (!Ptr.equalBaseIndex(BasePtr))
10725       break;
10726
10727     // The memory operands must not be volatile.
10728     if (Index->isVolatile() || Index->isIndexed())
10729       break;
10730
10731     // No truncation.
10732     if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
10733       if (St->isTruncatingStore())
10734         break;
10735
10736     // The stored memory type must be the same.
10737     if (Index->getMemoryVT() != MemVT)
10738       break;
10739
10740     // We found a potential memory operand to merge.
10741     StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
10742
10743     // Find the next memory operand in the chain. If the next operand in the
10744     // chain is a store then move up and continue the scan with the next
10745     // memory operand. If the next operand is a load save it and use alias
10746     // information to check if it interferes with anything.
10747     SDNode *NextInChain = Index->getChain().getNode();
10748     while (1) {
10749       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
10750         // We found a store node. Use it for the next iteration.
10751         Index = STn;
10752         break;
10753       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
10754         if (Ldn->isVolatile()) {
10755           Index = nullptr;
10756           break;
10757         }
10758
10759         // Save the load node for later. Continue the scan.
10760         AliasLoadNodes.push_back(Ldn);
10761         NextInChain = Ldn->getChain().getNode();
10762         continue;
10763       } else {
10764         Index = nullptr;
10765         break;
10766       }
10767     }
10768   }
10769
10770   // Check if there is anything to merge.
10771   if (StoreNodes.size() < 2)
10772     return false;
10773
10774   // Sort the memory operands according to their distance from the base pointer.
10775   std::sort(StoreNodes.begin(), StoreNodes.end(),
10776             [](MemOpLink LHS, MemOpLink RHS) {
10777     return LHS.OffsetFromBase < RHS.OffsetFromBase ||
10778            (LHS.OffsetFromBase == RHS.OffsetFromBase &&
10779             LHS.SequenceNum > RHS.SequenceNum);
10780   });
10781
10782   // Scan the memory operations on the chain and find the first non-consecutive
10783   // store memory address.
10784   unsigned LastConsecutiveStore = 0;
10785   int64_t StartAddress = StoreNodes[0].OffsetFromBase;
10786   for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
10787
10788     // Check that the addresses are consecutive starting from the second
10789     // element in the list of stores.
10790     if (i > 0) {
10791       int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
10792       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
10793         break;
10794     }
10795
10796     bool Alias = false;
10797     // Check if this store interferes with any of the loads that we found.
10798     for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
10799       if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
10800         Alias = true;
10801         break;
10802       }
10803     // We found a load that alias with this store. Stop the sequence.
10804     if (Alias)
10805       break;
10806
10807     // Mark this node as useful.
10808     LastConsecutiveStore = i;
10809   }
10810
10811   // The node with the lowest store address.
10812   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
10813   unsigned FirstStoreAS = FirstInChain->getAddressSpace();
10814   unsigned FirstStoreAlign = FirstInChain->getAlignment();
10815
10816   // Store the constants into memory as one consecutive store.
10817   if (IsConstantSrc) {
10818     unsigned LastLegalType = 0;
10819     unsigned LastLegalVectorType = 0;
10820     bool NonZero = false;
10821     for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
10822       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
10823       SDValue StoredVal = St->getValue();
10824
10825       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
10826         NonZero |= !C->isNullValue();
10827       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
10828         NonZero |= !C->getConstantFPValue()->isNullValue();
10829       } else {
10830         // Non-constant.
10831         break;
10832       }
10833
10834       // Find a legal type for the constant store.
10835       unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
10836       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10837       if (TLI.isTypeLegal(StoreTy) &&
10838           allowableAlignment(DAG, TLI, StoreTy, FirstStoreAS,
10839                              FirstStoreAlign)) {
10840         LastLegalType = i+1;
10841       // Or check whether a truncstore is legal.
10842       } else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
10843                  TargetLowering::TypePromoteInteger) {
10844         EVT LegalizedStoredValueTy =
10845           TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
10846         if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
10847             allowableAlignment(DAG, TLI, LegalizedStoredValueTy, FirstStoreAS,
10848                                FirstStoreAlign)) {
10849           LastLegalType = i + 1;
10850         }
10851       }
10852
10853       // Find a legal type for the vector store.
10854       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10855       if (TLI.isTypeLegal(Ty) &&
10856           allowableAlignment(DAG, TLI, Ty, FirstStoreAS, FirstStoreAlign)) {
10857         LastLegalVectorType = i + 1;
10858       }
10859     }
10860
10861     // We only use vectors if the constant is known to be zero and the
10862     // function is not marked with the noimplicitfloat attribute.
10863     if (NonZero || NoVectors)
10864       LastLegalVectorType = 0;
10865
10866     // Check if we found a legal integer type to store.
10867     if (LastLegalType == 0 && LastLegalVectorType == 0)
10868       return false;
10869
10870     bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
10871     unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
10872
10873     return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
10874                                            true, UseVector);
10875   }
10876
10877   // When extracting multiple vector elements, try to store them
10878   // in one vector store rather than a sequence of scalar stores.
10879   if (IsExtractVecEltSrc) {
10880     unsigned NumElem = 0;
10881     for (unsigned i = 0; i < LastConsecutiveStore + 1; ++i) {
10882       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
10883       SDValue StoredVal = St->getValue();
10884       // This restriction could be loosened.
10885       // Bail out if any stored values are not elements extracted from a vector.
10886       // It should be possible to handle mixed sources, but load sources need
10887       // more careful handling (see the block of code below that handles
10888       // consecutive loads).
10889       if (StoredVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10890         return false;
10891
10892       // Find a legal type for the vector store.
10893       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10894       if (TLI.isTypeLegal(Ty) &&
10895           allowableAlignment(DAG, TLI, Ty, FirstStoreAS, FirstStoreAlign))
10896         NumElem = i + 1;
10897     }
10898
10899     return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
10900                                            false, true);
10901   }
10902
10903   // Below we handle the case of multiple consecutive stores that
10904   // come from multiple consecutive loads. We merge them into a single
10905   // wide load and a single wide store.
10906
10907   // Look for load nodes which are used by the stored values.
10908   SmallVector<MemOpLink, 8> LoadNodes;
10909
10910   // Find acceptable loads. Loads need to have the same chain (token factor),
10911   // must not be zext, volatile, indexed, and they must be consecutive.
10912   BaseIndexOffset LdBasePtr;
10913   for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
10914     StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
10915     LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
10916     if (!Ld) break;
10917
10918     // Loads must only have one use.
10919     if (!Ld->hasNUsesOfValue(1, 0))
10920       break;
10921
10922     // The memory operands must not be volatile.
10923     if (Ld->isVolatile() || Ld->isIndexed())
10924       break;
10925
10926     // We do not accept ext loads.
10927     if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
10928       break;
10929
10930     // The stored memory type must be the same.
10931     if (Ld->getMemoryVT() != MemVT)
10932       break;
10933
10934     BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
10935     // If this is not the first ptr that we check.
10936     if (LdBasePtr.Base.getNode()) {
10937       // The base ptr must be the same.
10938       if (!LdPtr.equalBaseIndex(LdBasePtr))
10939         break;
10940     } else {
10941       // Check that all other base pointers are the same as this one.
10942       LdBasePtr = LdPtr;
10943     }
10944
10945     // We found a potential memory operand to merge.
10946     LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
10947   }
10948
10949   if (LoadNodes.size() < 2)
10950     return false;
10951
10952   // If we have load/store pair instructions and we only have two values,
10953   // don't bother.
10954   unsigned RequiredAlignment;
10955   if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
10956       St->getAlignment() >= RequiredAlignment)
10957     return false;
10958
10959   LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
10960   unsigned FirstLoadAS = FirstLoad->getAddressSpace();
10961   unsigned FirstLoadAlign = FirstLoad->getAlignment();
10962
10963   // Scan the memory operations on the chain and find the first non-consecutive
10964   // load memory address. These variables hold the index in the store node
10965   // array.
10966   unsigned LastConsecutiveLoad = 0;
10967   // This variable refers to the size and not index in the array.
10968   unsigned LastLegalVectorType = 0;
10969   unsigned LastLegalIntegerType = 0;
10970   StartAddress = LoadNodes[0].OffsetFromBase;
10971   SDValue FirstChain = FirstLoad->getChain();
10972   for (unsigned i = 1; i < LoadNodes.size(); ++i) {
10973     // All loads much share the same chain.
10974     if (LoadNodes[i].MemNode->getChain() != FirstChain)
10975       break;
10976
10977     int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
10978     if (CurrAddress - StartAddress != (ElementSizeBytes * i))
10979       break;
10980     LastConsecutiveLoad = i;
10981
10982     // Find a legal type for the vector store.
10983     EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10984     if (TLI.isTypeLegal(StoreTy) &&
10985         allowableAlignment(DAG, TLI, StoreTy, FirstStoreAS, FirstStoreAlign) &&
10986         allowableAlignment(DAG, TLI, StoreTy, FirstLoadAS, FirstLoadAlign)) {
10987       LastLegalVectorType = i + 1;
10988     }
10989
10990     // Find a legal type for the integer store.
10991     unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
10992     StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10993     if (TLI.isTypeLegal(StoreTy) &&
10994         allowableAlignment(DAG, TLI, StoreTy, FirstStoreAS, FirstStoreAlign) &&
10995         allowableAlignment(DAG, TLI, StoreTy, FirstLoadAS, FirstLoadAlign))
10996       LastLegalIntegerType = i + 1;
10997     // Or check whether a truncstore and extload is legal.
10998     else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
10999              TargetLowering::TypePromoteInteger) {
11000       EVT LegalizedStoredValueTy =
11001         TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
11002       if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
11003           TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11004           TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11005           TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11006           allowableAlignment(DAG, TLI, LegalizedStoredValueTy, FirstStoreAS,
11007                              FirstStoreAlign) &&
11008           allowableAlignment(DAG, TLI, LegalizedStoredValueTy, FirstLoadAS,
11009                              FirstLoadAlign))
11010         LastLegalIntegerType = i+1;
11011     }
11012   }
11013
11014   // Only use vector types if the vector type is larger than the integer type.
11015   // If they are the same, use integers.
11016   bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
11017   unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
11018
11019   // We add +1 here because the LastXXX variables refer to location while
11020   // the NumElem refers to array/index size.
11021   unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
11022   NumElem = std::min(LastLegalType, NumElem);
11023
11024   if (NumElem < 2)
11025     return false;
11026
11027   // The latest Node in the DAG.
11028   unsigned LatestNodeUsed = 0;
11029   for (unsigned i=1; i<NumElem; ++i) {
11030     // Find a chain for the new wide-store operand. Notice that some
11031     // of the store nodes that we found may not be selected for inclusion
11032     // in the wide store. The chain we use needs to be the chain of the
11033     // latest store node which is *used* and replaced by the wide store.
11034     if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
11035       LatestNodeUsed = i;
11036   }
11037
11038   LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
11039
11040   // Find if it is better to use vectors or integers to load and store
11041   // to memory.
11042   EVT JointMemOpVT;
11043   if (UseVectorTy) {
11044     JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
11045   } else {
11046     unsigned StoreBW = NumElem * ElementSizeBytes * 8;
11047     JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
11048   }
11049
11050   SDLoc LoadDL(LoadNodes[0].MemNode);
11051   SDLoc StoreDL(StoreNodes[0].MemNode);
11052
11053   SDValue NewLoad = DAG.getLoad(
11054       JointMemOpVT, LoadDL, FirstLoad->getChain(), FirstLoad->getBasePtr(),
11055       FirstLoad->getPointerInfo(), false, false, false, FirstLoadAlign);
11056
11057   SDValue NewStore = DAG.getStore(
11058       LatestOp->getChain(), StoreDL, NewLoad, FirstInChain->getBasePtr(),
11059       FirstInChain->getPointerInfo(), false, false, FirstStoreAlign);
11060
11061   // Replace one of the loads with the new load.
11062   LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
11063   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
11064                                 SDValue(NewLoad.getNode(), 1));
11065
11066   // Remove the rest of the load chains.
11067   for (unsigned i = 1; i < NumElem ; ++i) {
11068     // Replace all chain users of the old load nodes with the chain of the new
11069     // load node.
11070     LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
11071     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
11072   }
11073
11074   // Replace the last store with the new store.
11075   CombineTo(LatestOp, NewStore);
11076   // Erase all other stores.
11077   for (unsigned i = 0; i < NumElem ; ++i) {
11078     // Remove all Store nodes.
11079     if (StoreNodes[i].MemNode == LatestOp)
11080       continue;
11081     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11082     DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
11083     deleteAndRecombine(St);
11084   }
11085
11086   return true;
11087 }
11088
11089 SDValue DAGCombiner::visitSTORE(SDNode *N) {
11090   StoreSDNode *ST  = cast<StoreSDNode>(N);
11091   SDValue Chain = ST->getChain();
11092   SDValue Value = ST->getValue();
11093   SDValue Ptr   = ST->getBasePtr();
11094
11095   // If this is a store of a bit convert, store the input value if the
11096   // resultant store does not need a higher alignment than the original.
11097   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
11098       ST->isUnindexed()) {
11099     unsigned OrigAlign = ST->getAlignment();
11100     EVT SVT = Value.getOperand(0).getValueType();
11101     unsigned Align = TLI.getDataLayout()->
11102       getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
11103     if (Align <= OrigAlign &&
11104         ((!LegalOperations && !ST->isVolatile()) ||
11105          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
11106       return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
11107                           Ptr, ST->getPointerInfo(), ST->isVolatile(),
11108                           ST->isNonTemporal(), OrigAlign,
11109                           ST->getAAInfo());
11110   }
11111
11112   // Turn 'store undef, Ptr' -> nothing.
11113   if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
11114     return Chain;
11115
11116   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
11117   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
11118     // NOTE: If the original store is volatile, this transform must not increase
11119     // the number of stores.  For example, on x86-32 an f64 can be stored in one
11120     // processor operation but an i64 (which is not legal) requires two.  So the
11121     // transform should not be done in this case.
11122     if (Value.getOpcode() != ISD::TargetConstantFP) {
11123       SDValue Tmp;
11124       switch (CFP->getSimpleValueType(0).SimpleTy) {
11125       default: llvm_unreachable("Unknown FP type");
11126       case MVT::f16:    // We don't do this for these yet.
11127       case MVT::f80:
11128       case MVT::f128:
11129       case MVT::ppcf128:
11130         break;
11131       case MVT::f32:
11132         if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
11133             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
11134           ;
11135           Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
11136                               bitcastToAPInt().getZExtValue(), SDLoc(CFP),
11137                               MVT::i32);
11138           return DAG.getStore(Chain, SDLoc(N), Tmp,
11139                               Ptr, ST->getMemOperand());
11140         }
11141         break;
11142       case MVT::f64:
11143         if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
11144              !ST->isVolatile()) ||
11145             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
11146           ;
11147           Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
11148                                 getZExtValue(), SDLoc(CFP), MVT::i64);
11149           return DAG.getStore(Chain, SDLoc(N), Tmp,
11150                               Ptr, ST->getMemOperand());
11151         }
11152
11153         if (!ST->isVolatile() &&
11154             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
11155           // Many FP stores are not made apparent until after legalize, e.g. for
11156           // argument passing.  Since this is so common, custom legalize the
11157           // 64-bit integer store into two 32-bit stores.
11158           uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
11159           SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32);
11160           SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32);
11161           if (TLI.isBigEndian()) std::swap(Lo, Hi);
11162
11163           unsigned Alignment = ST->getAlignment();
11164           bool isVolatile = ST->isVolatile();
11165           bool isNonTemporal = ST->isNonTemporal();
11166           AAMDNodes AAInfo = ST->getAAInfo();
11167
11168           SDLoc DL(N);
11169
11170           SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
11171                                      Ptr, ST->getPointerInfo(),
11172                                      isVolatile, isNonTemporal,
11173                                      ST->getAlignment(), AAInfo);
11174           Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
11175                             DAG.getConstant(4, DL, Ptr.getValueType()));
11176           Alignment = MinAlign(Alignment, 4U);
11177           SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
11178                                      Ptr, ST->getPointerInfo().getWithOffset(4),
11179                                      isVolatile, isNonTemporal,
11180                                      Alignment, AAInfo);
11181           return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
11182                              St0, St1);
11183         }
11184
11185         break;
11186       }
11187     }
11188   }
11189
11190   // Try to infer better alignment information than the store already has.
11191   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
11192     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
11193       if (Align > ST->getAlignment()) {
11194         SDValue NewStore =
11195                DAG.getTruncStore(Chain, SDLoc(N), Value,
11196                                  Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
11197                                  ST->isVolatile(), ST->isNonTemporal(), Align,
11198                                  ST->getAAInfo());
11199         if (NewStore.getNode() != N)
11200           return CombineTo(ST, NewStore, true);
11201       }
11202     }
11203   }
11204
11205   // Try transforming a pair floating point load / store ops to integer
11206   // load / store ops.
11207   SDValue NewST = TransformFPLoadStorePair(N);
11208   if (NewST.getNode())
11209     return NewST;
11210
11211   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
11212                                                   : DAG.getSubtarget().useAA();
11213 #ifndef NDEBUG
11214   if (CombinerAAOnlyFunc.getNumOccurrences() &&
11215       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11216     UseAA = false;
11217 #endif
11218   if (UseAA && ST->isUnindexed()) {
11219     // Walk up chain skipping non-aliasing memory nodes.
11220     SDValue BetterChain = FindBetterChain(N, Chain);
11221
11222     // If there is a better chain.
11223     if (Chain != BetterChain) {
11224       SDValue ReplStore;
11225
11226       // Replace the chain to avoid dependency.
11227       if (ST->isTruncatingStore()) {
11228         ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
11229                                       ST->getMemoryVT(), ST->getMemOperand());
11230       } else {
11231         ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
11232                                  ST->getMemOperand());
11233       }
11234
11235       // Create token to keep both nodes around.
11236       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
11237                                   MVT::Other, Chain, ReplStore);
11238
11239       // Make sure the new and old chains are cleaned up.
11240       AddToWorklist(Token.getNode());
11241
11242       // Don't add users to work list.
11243       return CombineTo(N, Token, false);
11244     }
11245   }
11246
11247   // Try transforming N to an indexed store.
11248   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
11249     return SDValue(N, 0);
11250
11251   // FIXME: is there such a thing as a truncating indexed store?
11252   if (ST->isTruncatingStore() && ST->isUnindexed() &&
11253       Value.getValueType().isInteger()) {
11254     // See if we can simplify the input to this truncstore with knowledge that
11255     // only the low bits are being used.  For example:
11256     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
11257     SDValue Shorter =
11258       GetDemandedBits(Value,
11259                       APInt::getLowBitsSet(
11260                         Value.getValueType().getScalarType().getSizeInBits(),
11261                         ST->getMemoryVT().getScalarType().getSizeInBits()));
11262     AddToWorklist(Value.getNode());
11263     if (Shorter.getNode())
11264       return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
11265                                Ptr, ST->getMemoryVT(), ST->getMemOperand());
11266
11267     // Otherwise, see if we can simplify the operation with
11268     // SimplifyDemandedBits, which only works if the value has a single use.
11269     if (SimplifyDemandedBits(Value,
11270                         APInt::getLowBitsSet(
11271                           Value.getValueType().getScalarType().getSizeInBits(),
11272                           ST->getMemoryVT().getScalarType().getSizeInBits())))
11273       return SDValue(N, 0);
11274   }
11275
11276   // If this is a load followed by a store to the same location, then the store
11277   // is dead/noop.
11278   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
11279     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
11280         ST->isUnindexed() && !ST->isVolatile() &&
11281         // There can't be any side effects between the load and store, such as
11282         // a call or store.
11283         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
11284       // The store is dead, remove it.
11285       return Chain;
11286     }
11287   }
11288
11289   // If this is a store followed by a store with the same value to the same
11290   // location, then the store is dead/noop.
11291   if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
11292     if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() &&
11293         ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() &&
11294         ST1->isUnindexed() && !ST1->isVolatile()) {
11295       // The store is dead, remove it.
11296       return Chain;
11297     }
11298   }
11299
11300   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
11301   // truncating store.  We can do this even if this is already a truncstore.
11302   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
11303       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
11304       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
11305                             ST->getMemoryVT())) {
11306     return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
11307                              Ptr, ST->getMemoryVT(), ST->getMemOperand());
11308   }
11309
11310   // Only perform this optimization before the types are legal, because we
11311   // don't want to perform this optimization on every DAGCombine invocation.
11312   if (!LegalTypes) {
11313     bool EverChanged = false;
11314
11315     do {
11316       // There can be multiple store sequences on the same chain.
11317       // Keep trying to merge store sequences until we are unable to do so
11318       // or until we merge the last store on the chain.
11319       bool Changed = MergeConsecutiveStores(ST);
11320       EverChanged |= Changed;
11321       if (!Changed) break;
11322     } while (ST->getOpcode() != ISD::DELETED_NODE);
11323
11324     if (EverChanged)
11325       return SDValue(N, 0);
11326   }
11327
11328   return ReduceLoadOpStoreWidth(N);
11329 }
11330
11331 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
11332   SDValue InVec = N->getOperand(0);
11333   SDValue InVal = N->getOperand(1);
11334   SDValue EltNo = N->getOperand(2);
11335   SDLoc dl(N);
11336
11337   // If the inserted element is an UNDEF, just use the input vector.
11338   if (InVal.getOpcode() == ISD::UNDEF)
11339     return InVec;
11340
11341   EVT VT = InVec.getValueType();
11342
11343   // If we can't generate a legal BUILD_VECTOR, exit
11344   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
11345     return SDValue();
11346
11347   // Check that we know which element is being inserted
11348   if (!isa<ConstantSDNode>(EltNo))
11349     return SDValue();
11350   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11351
11352   // Canonicalize insert_vector_elt dag nodes.
11353   // Example:
11354   // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
11355   // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
11356   //
11357   // Do this only if the child insert_vector node has one use; also
11358   // do this only if indices are both constants and Idx1 < Idx0.
11359   if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
11360       && isa<ConstantSDNode>(InVec.getOperand(2))) {
11361     unsigned OtherElt =
11362       cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
11363     if (Elt < OtherElt) {
11364       // Swap nodes.
11365       SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
11366                                   InVec.getOperand(0), InVal, EltNo);
11367       AddToWorklist(NewOp.getNode());
11368       return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
11369                          VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
11370     }
11371   }
11372
11373   // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
11374   // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
11375   // vector elements.
11376   SmallVector<SDValue, 8> Ops;
11377   // Do not combine these two vectors if the output vector will not replace
11378   // the input vector.
11379   if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
11380     Ops.append(InVec.getNode()->op_begin(),
11381                InVec.getNode()->op_end());
11382   } else if (InVec.getOpcode() == ISD::UNDEF) {
11383     unsigned NElts = VT.getVectorNumElements();
11384     Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
11385   } else {
11386     return SDValue();
11387   }
11388
11389   // Insert the element
11390   if (Elt < Ops.size()) {
11391     // All the operands of BUILD_VECTOR must have the same type;
11392     // we enforce that here.
11393     EVT OpVT = Ops[0].getValueType();
11394     if (InVal.getValueType() != OpVT)
11395       InVal = OpVT.bitsGT(InVal.getValueType()) ?
11396                 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
11397                 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
11398     Ops[Elt] = InVal;
11399   }
11400
11401   // Return the new vector
11402   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
11403 }
11404
11405 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
11406     SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
11407   EVT ResultVT = EVE->getValueType(0);
11408   EVT VecEltVT = InVecVT.getVectorElementType();
11409   unsigned Align = OriginalLoad->getAlignment();
11410   unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
11411       VecEltVT.getTypeForEVT(*DAG.getContext()));
11412
11413   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
11414     return SDValue();
11415
11416   Align = NewAlign;
11417
11418   SDValue NewPtr = OriginalLoad->getBasePtr();
11419   SDValue Offset;
11420   EVT PtrType = NewPtr.getValueType();
11421   MachinePointerInfo MPI;
11422   SDLoc DL(EVE);
11423   if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
11424     int Elt = ConstEltNo->getZExtValue();
11425     unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
11426     Offset = DAG.getConstant(PtrOff, DL, PtrType);
11427     MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
11428   } else {
11429     Offset = DAG.getZExtOrTrunc(EltNo, DL, PtrType);
11430     Offset = DAG.getNode(
11431         ISD::MUL, DL, PtrType, Offset,
11432         DAG.getConstant(VecEltVT.getStoreSize(), DL, PtrType));
11433     MPI = OriginalLoad->getPointerInfo();
11434   }
11435   NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, NewPtr, Offset);
11436
11437   // The replacement we need to do here is a little tricky: we need to
11438   // replace an extractelement of a load with a load.
11439   // Use ReplaceAllUsesOfValuesWith to do the replacement.
11440   // Note that this replacement assumes that the extractvalue is the only
11441   // use of the load; that's okay because we don't want to perform this
11442   // transformation in other cases anyway.
11443   SDValue Load;
11444   SDValue Chain;
11445   if (ResultVT.bitsGT(VecEltVT)) {
11446     // If the result type of vextract is wider than the load, then issue an
11447     // extending load instead.
11448     ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT,
11449                                                   VecEltVT)
11450                                    ? ISD::ZEXTLOAD
11451                                    : ISD::EXTLOAD;
11452     Load = DAG.getExtLoad(
11453         ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI,
11454         VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
11455         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
11456     Chain = Load.getValue(1);
11457   } else {
11458     Load = DAG.getLoad(
11459         VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
11460         OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
11461         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
11462     Chain = Load.getValue(1);
11463     if (ResultVT.bitsLT(VecEltVT))
11464       Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
11465     else
11466       Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
11467   }
11468   WorklistRemover DeadNodes(*this);
11469   SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
11470   SDValue To[] = { Load, Chain };
11471   DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
11472   // Since we're explicitly calling ReplaceAllUses, add the new node to the
11473   // worklist explicitly as well.
11474   AddToWorklist(Load.getNode());
11475   AddUsersToWorklist(Load.getNode()); // Add users too
11476   // Make sure to revisit this node to clean it up; it will usually be dead.
11477   AddToWorklist(EVE);
11478   ++OpsNarrowed;
11479   return SDValue(EVE, 0);
11480 }
11481
11482 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
11483   // (vextract (scalar_to_vector val, 0) -> val
11484   SDValue InVec = N->getOperand(0);
11485   EVT VT = InVec.getValueType();
11486   EVT NVT = N->getValueType(0);
11487
11488   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
11489     // Check if the result type doesn't match the inserted element type. A
11490     // SCALAR_TO_VECTOR may truncate the inserted element and the
11491     // EXTRACT_VECTOR_ELT may widen the extracted vector.
11492     SDValue InOp = InVec.getOperand(0);
11493     if (InOp.getValueType() != NVT) {
11494       assert(InOp.getValueType().isInteger() && NVT.isInteger());
11495       return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
11496     }
11497     return InOp;
11498   }
11499
11500   SDValue EltNo = N->getOperand(1);
11501   bool ConstEltNo = isa<ConstantSDNode>(EltNo);
11502
11503   // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
11504   // We only perform this optimization before the op legalization phase because
11505   // we may introduce new vector instructions which are not backed by TD
11506   // patterns. For example on AVX, extracting elements from a wide vector
11507   // without using extract_subvector. However, if we can find an underlying
11508   // scalar value, then we can always use that.
11509   if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
11510       && ConstEltNo) {
11511     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11512     int NumElem = VT.getVectorNumElements();
11513     ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
11514     // Find the new index to extract from.
11515     int OrigElt = SVOp->getMaskElt(Elt);
11516
11517     // Extracting an undef index is undef.
11518     if (OrigElt == -1)
11519       return DAG.getUNDEF(NVT);
11520
11521     // Select the right vector half to extract from.
11522     SDValue SVInVec;
11523     if (OrigElt < NumElem) {
11524       SVInVec = InVec->getOperand(0);
11525     } else {
11526       SVInVec = InVec->getOperand(1);
11527       OrigElt -= NumElem;
11528     }
11529
11530     if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
11531       SDValue InOp = SVInVec.getOperand(OrigElt);
11532       if (InOp.getValueType() != NVT) {
11533         assert(InOp.getValueType().isInteger() && NVT.isInteger());
11534         InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
11535       }
11536
11537       return InOp;
11538     }
11539
11540     // FIXME: We should handle recursing on other vector shuffles and
11541     // scalar_to_vector here as well.
11542
11543     if (!LegalOperations) {
11544       EVT IndexTy = TLI.getVectorIdxTy();
11545       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, SVInVec,
11546                          DAG.getConstant(OrigElt, SDLoc(SVOp), IndexTy));
11547     }
11548   }
11549
11550   bool BCNumEltsChanged = false;
11551   EVT ExtVT = VT.getVectorElementType();
11552   EVT LVT = ExtVT;
11553
11554   // If the result of load has to be truncated, then it's not necessarily
11555   // profitable.
11556   if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
11557     return SDValue();
11558
11559   if (InVec.getOpcode() == ISD::BITCAST) {
11560     // Don't duplicate a load with other uses.
11561     if (!InVec.hasOneUse())
11562       return SDValue();
11563
11564     EVT BCVT = InVec.getOperand(0).getValueType();
11565     if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
11566       return SDValue();
11567     if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
11568       BCNumEltsChanged = true;
11569     InVec = InVec.getOperand(0);
11570     ExtVT = BCVT.getVectorElementType();
11571   }
11572
11573   // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
11574   if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
11575       ISD::isNormalLoad(InVec.getNode()) &&
11576       !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
11577     SDValue Index = N->getOperand(1);
11578     if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
11579       return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
11580                                                            OrigLoad);
11581   }
11582
11583   // Perform only after legalization to ensure build_vector / vector_shuffle
11584   // optimizations have already been done.
11585   if (!LegalOperations) return SDValue();
11586
11587   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
11588   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
11589   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
11590
11591   if (ConstEltNo) {
11592     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11593
11594     LoadSDNode *LN0 = nullptr;
11595     const ShuffleVectorSDNode *SVN = nullptr;
11596     if (ISD::isNormalLoad(InVec.getNode())) {
11597       LN0 = cast<LoadSDNode>(InVec);
11598     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
11599                InVec.getOperand(0).getValueType() == ExtVT &&
11600                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
11601       // Don't duplicate a load with other uses.
11602       if (!InVec.hasOneUse())
11603         return SDValue();
11604
11605       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
11606     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
11607       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
11608       // =>
11609       // (load $addr+1*size)
11610
11611       // Don't duplicate a load with other uses.
11612       if (!InVec.hasOneUse())
11613         return SDValue();
11614
11615       // If the bit convert changed the number of elements, it is unsafe
11616       // to examine the mask.
11617       if (BCNumEltsChanged)
11618         return SDValue();
11619
11620       // Select the input vector, guarding against out of range extract vector.
11621       unsigned NumElems = VT.getVectorNumElements();
11622       int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
11623       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
11624
11625       if (InVec.getOpcode() == ISD::BITCAST) {
11626         // Don't duplicate a load with other uses.
11627         if (!InVec.hasOneUse())
11628           return SDValue();
11629
11630         InVec = InVec.getOperand(0);
11631       }
11632       if (ISD::isNormalLoad(InVec.getNode())) {
11633         LN0 = cast<LoadSDNode>(InVec);
11634         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
11635         EltNo = DAG.getConstant(Elt, SDLoc(EltNo), EltNo.getValueType());
11636       }
11637     }
11638
11639     // Make sure we found a non-volatile load and the extractelement is
11640     // the only use.
11641     if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
11642       return SDValue();
11643
11644     // If Idx was -1 above, Elt is going to be -1, so just return undef.
11645     if (Elt == -1)
11646       return DAG.getUNDEF(LVT);
11647
11648     return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
11649   }
11650
11651   return SDValue();
11652 }
11653
11654 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
11655 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
11656   // We perform this optimization post type-legalization because
11657   // the type-legalizer often scalarizes integer-promoted vectors.
11658   // Performing this optimization before may create bit-casts which
11659   // will be type-legalized to complex code sequences.
11660   // We perform this optimization only before the operation legalizer because we
11661   // may introduce illegal operations.
11662   if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
11663     return SDValue();
11664
11665   unsigned NumInScalars = N->getNumOperands();
11666   SDLoc dl(N);
11667   EVT VT = N->getValueType(0);
11668
11669   // Check to see if this is a BUILD_VECTOR of a bunch of values
11670   // which come from any_extend or zero_extend nodes. If so, we can create
11671   // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
11672   // optimizations. We do not handle sign-extend because we can't fill the sign
11673   // using shuffles.
11674   EVT SourceType = MVT::Other;
11675   bool AllAnyExt = true;
11676
11677   for (unsigned i = 0; i != NumInScalars; ++i) {
11678     SDValue In = N->getOperand(i);
11679     // Ignore undef inputs.
11680     if (In.getOpcode() == ISD::UNDEF) continue;
11681
11682     bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
11683     bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
11684
11685     // Abort if the element is not an extension.
11686     if (!ZeroExt && !AnyExt) {
11687       SourceType = MVT::Other;
11688       break;
11689     }
11690
11691     // The input is a ZeroExt or AnyExt. Check the original type.
11692     EVT InTy = In.getOperand(0).getValueType();
11693
11694     // Check that all of the widened source types are the same.
11695     if (SourceType == MVT::Other)
11696       // First time.
11697       SourceType = InTy;
11698     else if (InTy != SourceType) {
11699       // Multiple income types. Abort.
11700       SourceType = MVT::Other;
11701       break;
11702     }
11703
11704     // Check if all of the extends are ANY_EXTENDs.
11705     AllAnyExt &= AnyExt;
11706   }
11707
11708   // In order to have valid types, all of the inputs must be extended from the
11709   // same source type and all of the inputs must be any or zero extend.
11710   // Scalar sizes must be a power of two.
11711   EVT OutScalarTy = VT.getScalarType();
11712   bool ValidTypes = SourceType != MVT::Other &&
11713                  isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
11714                  isPowerOf2_32(SourceType.getSizeInBits());
11715
11716   // Create a new simpler BUILD_VECTOR sequence which other optimizations can
11717   // turn into a single shuffle instruction.
11718   if (!ValidTypes)
11719     return SDValue();
11720
11721   bool isLE = TLI.isLittleEndian();
11722   unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
11723   assert(ElemRatio > 1 && "Invalid element size ratio");
11724   SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
11725                                DAG.getConstant(0, SDLoc(N), SourceType);
11726
11727   unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
11728   SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
11729
11730   // Populate the new build_vector
11731   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
11732     SDValue Cast = N->getOperand(i);
11733     assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
11734             Cast.getOpcode() == ISD::ZERO_EXTEND ||
11735             Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
11736     SDValue In;
11737     if (Cast.getOpcode() == ISD::UNDEF)
11738       In = DAG.getUNDEF(SourceType);
11739     else
11740       In = Cast->getOperand(0);
11741     unsigned Index = isLE ? (i * ElemRatio) :
11742                             (i * ElemRatio + (ElemRatio - 1));
11743
11744     assert(Index < Ops.size() && "Invalid index");
11745     Ops[Index] = In;
11746   }
11747
11748   // The type of the new BUILD_VECTOR node.
11749   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
11750   assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
11751          "Invalid vector size");
11752   // Check if the new vector type is legal.
11753   if (!isTypeLegal(VecVT)) return SDValue();
11754
11755   // Make the new BUILD_VECTOR.
11756   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
11757
11758   // The new BUILD_VECTOR node has the potential to be further optimized.
11759   AddToWorklist(BV.getNode());
11760   // Bitcast to the desired type.
11761   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
11762 }
11763
11764 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
11765   EVT VT = N->getValueType(0);
11766
11767   unsigned NumInScalars = N->getNumOperands();
11768   SDLoc dl(N);
11769
11770   EVT SrcVT = MVT::Other;
11771   unsigned Opcode = ISD::DELETED_NODE;
11772   unsigned NumDefs = 0;
11773
11774   for (unsigned i = 0; i != NumInScalars; ++i) {
11775     SDValue In = N->getOperand(i);
11776     unsigned Opc = In.getOpcode();
11777
11778     if (Opc == ISD::UNDEF)
11779       continue;
11780
11781     // If all scalar values are floats and converted from integers.
11782     if (Opcode == ISD::DELETED_NODE &&
11783         (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
11784       Opcode = Opc;
11785     }
11786
11787     if (Opc != Opcode)
11788       return SDValue();
11789
11790     EVT InVT = In.getOperand(0).getValueType();
11791
11792     // If all scalar values are typed differently, bail out. It's chosen to
11793     // simplify BUILD_VECTOR of integer types.
11794     if (SrcVT == MVT::Other)
11795       SrcVT = InVT;
11796     if (SrcVT != InVT)
11797       return SDValue();
11798     NumDefs++;
11799   }
11800
11801   // If the vector has just one element defined, it's not worth to fold it into
11802   // a vectorized one.
11803   if (NumDefs < 2)
11804     return SDValue();
11805
11806   assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
11807          && "Should only handle conversion from integer to float.");
11808   assert(SrcVT != MVT::Other && "Cannot determine source type!");
11809
11810   EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
11811
11812   if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
11813     return SDValue();
11814
11815   // Just because the floating-point vector type is legal does not necessarily
11816   // mean that the corresponding integer vector type is.
11817   if (!isTypeLegal(NVT))
11818     return SDValue();
11819
11820   SmallVector<SDValue, 8> Opnds;
11821   for (unsigned i = 0; i != NumInScalars; ++i) {
11822     SDValue In = N->getOperand(i);
11823
11824     if (In.getOpcode() == ISD::UNDEF)
11825       Opnds.push_back(DAG.getUNDEF(SrcVT));
11826     else
11827       Opnds.push_back(In.getOperand(0));
11828   }
11829   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
11830   AddToWorklist(BV.getNode());
11831
11832   return DAG.getNode(Opcode, dl, VT, BV);
11833 }
11834
11835 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
11836   unsigned NumInScalars = N->getNumOperands();
11837   SDLoc dl(N);
11838   EVT VT = N->getValueType(0);
11839
11840   // A vector built entirely of undefs is undef.
11841   if (ISD::allOperandsUndef(N))
11842     return DAG.getUNDEF(VT);
11843
11844   if (SDValue V = reduceBuildVecExtToExtBuildVec(N))
11845     return V;
11846
11847   if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N))
11848     return V;
11849
11850   // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
11851   // operations.  If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
11852   // at most two distinct vectors, turn this into a shuffle node.
11853
11854   // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
11855   if (!isTypeLegal(VT))
11856     return SDValue();
11857
11858   // May only combine to shuffle after legalize if shuffle is legal.
11859   if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
11860     return SDValue();
11861
11862   SDValue VecIn1, VecIn2;
11863   bool UsesZeroVector = false;
11864   for (unsigned i = 0; i != NumInScalars; ++i) {
11865     SDValue Op = N->getOperand(i);
11866     // Ignore undef inputs.
11867     if (Op.getOpcode() == ISD::UNDEF) continue;
11868
11869     // See if we can combine this build_vector into a blend with a zero vector.
11870     if (!VecIn2.getNode() && (isNullConstant(Op) ||
11871         (Op.getOpcode() == ISD::ConstantFP &&
11872         cast<ConstantFPSDNode>(Op.getNode())->getValueAPF().isZero()))) {
11873       UsesZeroVector = true;
11874       continue;
11875     }
11876
11877     // If this input is something other than a EXTRACT_VECTOR_ELT with a
11878     // constant index, bail out.
11879     if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
11880         !isa<ConstantSDNode>(Op.getOperand(1))) {
11881       VecIn1 = VecIn2 = SDValue(nullptr, 0);
11882       break;
11883     }
11884
11885     // We allow up to two distinct input vectors.
11886     SDValue ExtractedFromVec = Op.getOperand(0);
11887     if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
11888       continue;
11889
11890     if (!VecIn1.getNode()) {
11891       VecIn1 = ExtractedFromVec;
11892     } else if (!VecIn2.getNode() && !UsesZeroVector) {
11893       VecIn2 = ExtractedFromVec;
11894     } else {
11895       // Too many inputs.
11896       VecIn1 = VecIn2 = SDValue(nullptr, 0);
11897       break;
11898     }
11899   }
11900
11901   // If everything is good, we can make a shuffle operation.
11902   if (VecIn1.getNode()) {
11903     unsigned InNumElements = VecIn1.getValueType().getVectorNumElements();
11904     SmallVector<int, 8> Mask;
11905     for (unsigned i = 0; i != NumInScalars; ++i) {
11906       unsigned Opcode = N->getOperand(i).getOpcode();
11907       if (Opcode == ISD::UNDEF) {
11908         Mask.push_back(-1);
11909         continue;
11910       }
11911
11912       // Operands can also be zero.
11913       if (Opcode != ISD::EXTRACT_VECTOR_ELT) {
11914         assert(UsesZeroVector &&
11915                (Opcode == ISD::Constant || Opcode == ISD::ConstantFP) &&
11916                "Unexpected node found!");
11917         Mask.push_back(NumInScalars+i);
11918         continue;
11919       }
11920
11921       // If extracting from the first vector, just use the index directly.
11922       SDValue Extract = N->getOperand(i);
11923       SDValue ExtVal = Extract.getOperand(1);
11924       unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
11925       if (Extract.getOperand(0) == VecIn1) {
11926         Mask.push_back(ExtIndex);
11927         continue;
11928       }
11929
11930       // Otherwise, use InIdx + InputVecSize
11931       Mask.push_back(InNumElements + ExtIndex);
11932     }
11933
11934     // Avoid introducing illegal shuffles with zero.
11935     if (UsesZeroVector && !TLI.isVectorClearMaskLegal(Mask, VT))
11936       return SDValue();
11937
11938     // We can't generate a shuffle node with mismatched input and output types.
11939     // Attempt to transform a single input vector to the correct type.
11940     if ((VT != VecIn1.getValueType())) {
11941       // If the input vector type has a different base type to the output
11942       // vector type, bail out.
11943       EVT VTElemType = VT.getVectorElementType();
11944       if ((VecIn1.getValueType().getVectorElementType() != VTElemType) ||
11945           (VecIn2.getNode() &&
11946            (VecIn2.getValueType().getVectorElementType() != VTElemType)))
11947         return SDValue();
11948
11949       // If the input vector is too small, widen it.
11950       // We only support widening of vectors which are half the size of the
11951       // output registers. For example XMM->YMM widening on X86 with AVX.
11952       EVT VecInT = VecIn1.getValueType();
11953       if (VecInT.getSizeInBits() * 2 == VT.getSizeInBits()) {
11954         // If we only have one small input, widen it by adding undef values.
11955         if (!VecIn2.getNode())
11956           VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1,
11957                                DAG.getUNDEF(VecIn1.getValueType()));
11958         else if (VecIn1.getValueType() == VecIn2.getValueType()) {
11959           // If we have two small inputs of the same type, try to concat them.
11960           VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1, VecIn2);
11961           VecIn2 = SDValue(nullptr, 0);
11962         } else
11963           return SDValue();
11964       } else if (VecInT.getSizeInBits() == VT.getSizeInBits() * 2) {
11965         // If the input vector is too large, try to split it.
11966         // We don't support having two input vectors that are too large.
11967         // If the zero vector was used, we can not split the vector,
11968         // since we'd need 3 inputs.
11969         if (UsesZeroVector || VecIn2.getNode())
11970           return SDValue();
11971
11972         if (!TLI.isExtractSubvectorCheap(VT, VT.getVectorNumElements()))
11973           return SDValue();
11974
11975         // Try to replace VecIn1 with two extract_subvectors
11976         // No need to update the masks, they should still be correct.
11977         VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
11978           DAG.getConstant(VT.getVectorNumElements(), dl, TLI.getVectorIdxTy()));
11979         VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
11980           DAG.getConstant(0, dl, TLI.getVectorIdxTy()));
11981       } else
11982         return SDValue();
11983     }
11984
11985     if (UsesZeroVector)
11986       VecIn2 = VT.isInteger() ? DAG.getConstant(0, dl, VT) :
11987                                 DAG.getConstantFP(0.0, dl, VT);
11988     else
11989       // If VecIn2 is unused then change it to undef.
11990       VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
11991
11992     // Check that we were able to transform all incoming values to the same
11993     // type.
11994     if (VecIn2.getValueType() != VecIn1.getValueType() ||
11995         VecIn1.getValueType() != VT)
11996           return SDValue();
11997
11998     // Return the new VECTOR_SHUFFLE node.
11999     SDValue Ops[2];
12000     Ops[0] = VecIn1;
12001     Ops[1] = VecIn2;
12002     return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
12003   }
12004
12005   return SDValue();
12006 }
12007
12008 static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) {
12009   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12010   EVT OpVT = N->getOperand(0).getValueType();
12011
12012   // If the operands are legal vectors, leave them alone.
12013   if (TLI.isTypeLegal(OpVT))
12014     return SDValue();
12015
12016   SDLoc DL(N);
12017   EVT VT = N->getValueType(0);
12018   SmallVector<SDValue, 8> Ops;
12019
12020   EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits());
12021   SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
12022
12023   // Keep track of what we encounter.
12024   bool AnyInteger = false;
12025   bool AnyFP = false;
12026   for (const SDValue &Op : N->ops()) {
12027     if (ISD::BITCAST == Op.getOpcode() &&
12028         !Op.getOperand(0).getValueType().isVector())
12029       Ops.push_back(Op.getOperand(0));
12030     else if (ISD::UNDEF == Op.getOpcode())
12031       Ops.push_back(ScalarUndef);
12032     else
12033       return SDValue();
12034
12035     // Note whether we encounter an integer or floating point scalar.
12036     // If it's neither, bail out, it could be something weird like x86mmx.
12037     EVT LastOpVT = Ops.back().getValueType();
12038     if (LastOpVT.isFloatingPoint())
12039       AnyFP = true;
12040     else if (LastOpVT.isInteger())
12041       AnyInteger = true;
12042     else
12043       return SDValue();
12044   }
12045
12046   // If any of the operands is a floating point scalar bitcast to a vector,
12047   // use floating point types throughout, and bitcast everything.  
12048   // Replace UNDEFs by another scalar UNDEF node, of the final desired type.
12049   if (AnyFP) {
12050     SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits());
12051     ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
12052     if (AnyInteger) {
12053       for (SDValue &Op : Ops) {
12054         if (Op.getValueType() == SVT)
12055           continue;
12056         if (Op.getOpcode() == ISD::UNDEF)
12057           Op = ScalarUndef;
12058         else
12059           Op = DAG.getNode(ISD::BITCAST, DL, SVT, Op);
12060       }
12061     }
12062   }
12063
12064   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT,
12065                                VT.getSizeInBits() / SVT.getSizeInBits());
12066   return DAG.getNode(ISD::BITCAST, DL, VT,
12067                      DAG.getNode(ISD::BUILD_VECTOR, DL, VecVT, Ops));
12068 }
12069
12070 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
12071   // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
12072   // EXTRACT_SUBVECTOR operations.  If so, and if the EXTRACT_SUBVECTOR vector
12073   // inputs come from at most two distinct vectors, turn this into a shuffle
12074   // node.
12075
12076   // If we only have one input vector, we don't need to do any concatenation.
12077   if (N->getNumOperands() == 1)
12078     return N->getOperand(0);
12079
12080   // Check if all of the operands are undefs.
12081   EVT VT = N->getValueType(0);
12082   if (ISD::allOperandsUndef(N))
12083     return DAG.getUNDEF(VT);
12084
12085   // Optimize concat_vectors where all but the first of the vectors are undef.
12086   if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) {
12087         return Op.getOpcode() == ISD::UNDEF;
12088       })) {
12089     SDValue In = N->getOperand(0);
12090     assert(In.getValueType().isVector() && "Must concat vectors");
12091
12092     // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
12093     if (In->getOpcode() == ISD::BITCAST &&
12094         !In->getOperand(0)->getValueType(0).isVector()) {
12095       SDValue Scalar = In->getOperand(0);
12096
12097       // If the bitcast type isn't legal, it might be a trunc of a legal type;
12098       // look through the trunc so we can still do the transform:
12099       //   concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar)
12100       if (Scalar->getOpcode() == ISD::TRUNCATE &&
12101           !TLI.isTypeLegal(Scalar.getValueType()) &&
12102           TLI.isTypeLegal(Scalar->getOperand(0).getValueType()))
12103         Scalar = Scalar->getOperand(0);
12104
12105       EVT SclTy = Scalar->getValueType(0);
12106
12107       if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
12108         return SDValue();
12109
12110       EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
12111                                  VT.getSizeInBits() / SclTy.getSizeInBits());
12112       if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
12113         return SDValue();
12114
12115       SDLoc dl = SDLoc(N);
12116       SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
12117       return DAG.getNode(ISD::BITCAST, dl, VT, Res);
12118     }
12119   }
12120
12121   // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR.
12122   // We have already tested above for an UNDEF only concatenation.
12123   // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
12124   // -> (BUILD_VECTOR A, B, ..., C, D, ...)
12125   auto IsBuildVectorOrUndef = [](const SDValue &Op) {
12126     return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode();
12127   };
12128   bool AllBuildVectorsOrUndefs =
12129       std::all_of(N->op_begin(), N->op_end(), IsBuildVectorOrUndef);
12130   if (AllBuildVectorsOrUndefs) {
12131     SmallVector<SDValue, 8> Opnds;
12132     EVT SVT = VT.getScalarType();
12133
12134     EVT MinVT = SVT;
12135     if (!SVT.isFloatingPoint()) {
12136       // If BUILD_VECTOR are from built from integer, they may have different
12137       // operand types. Get the smallest type and truncate all operands to it.
12138       bool FoundMinVT = false;
12139       for (const SDValue &Op : N->ops())
12140         if (ISD::BUILD_VECTOR == Op.getOpcode()) {
12141           EVT OpSVT = Op.getOperand(0)->getValueType(0);
12142           MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT;
12143           FoundMinVT = true;
12144         }
12145       assert(FoundMinVT && "Concat vector type mismatch");
12146     }
12147
12148     for (const SDValue &Op : N->ops()) {
12149       EVT OpVT = Op.getValueType();
12150       unsigned NumElts = OpVT.getVectorNumElements();
12151
12152       if (ISD::UNDEF == Op.getOpcode())
12153         Opnds.append(NumElts, DAG.getUNDEF(MinVT));
12154
12155       if (ISD::BUILD_VECTOR == Op.getOpcode()) {
12156         if (SVT.isFloatingPoint()) {
12157           assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch");
12158           Opnds.append(Op->op_begin(), Op->op_begin() + NumElts);
12159         } else {
12160           for (unsigned i = 0; i != NumElts; ++i)
12161             Opnds.push_back(
12162                 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i)));
12163         }
12164       }
12165     }
12166
12167     assert(VT.getVectorNumElements() == Opnds.size() &&
12168            "Concat vector type mismatch");
12169     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
12170   }
12171
12172   // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR.
12173   if (SDValue V = combineConcatVectorOfScalars(N, DAG))
12174     return V;
12175
12176   // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
12177   // nodes often generate nop CONCAT_VECTOR nodes.
12178   // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
12179   // place the incoming vectors at the exact same location.
12180   SDValue SingleSource = SDValue();
12181   unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
12182
12183   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
12184     SDValue Op = N->getOperand(i);
12185
12186     if (Op.getOpcode() == ISD::UNDEF)
12187       continue;
12188
12189     // Check if this is the identity extract:
12190     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
12191       return SDValue();
12192
12193     // Find the single incoming vector for the extract_subvector.
12194     if (SingleSource.getNode()) {
12195       if (Op.getOperand(0) != SingleSource)
12196         return SDValue();
12197     } else {
12198       SingleSource = Op.getOperand(0);
12199
12200       // Check the source type is the same as the type of the result.
12201       // If not, this concat may extend the vector, so we can not
12202       // optimize it away.
12203       if (SingleSource.getValueType() != N->getValueType(0))
12204         return SDValue();
12205     }
12206
12207     unsigned IdentityIndex = i * PartNumElem;
12208     ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
12209     // The extract index must be constant.
12210     if (!CS)
12211       return SDValue();
12212
12213     // Check that we are reading from the identity index.
12214     if (CS->getZExtValue() != IdentityIndex)
12215       return SDValue();
12216   }
12217
12218   if (SingleSource.getNode())
12219     return SingleSource;
12220
12221   return SDValue();
12222 }
12223
12224 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
12225   EVT NVT = N->getValueType(0);
12226   SDValue V = N->getOperand(0);
12227
12228   if (V->getOpcode() == ISD::CONCAT_VECTORS) {
12229     // Combine:
12230     //    (extract_subvec (concat V1, V2, ...), i)
12231     // Into:
12232     //    Vi if possible
12233     // Only operand 0 is checked as 'concat' assumes all inputs of the same
12234     // type.
12235     if (V->getOperand(0).getValueType() != NVT)
12236       return SDValue();
12237     unsigned Idx = N->getConstantOperandVal(1);
12238     unsigned NumElems = NVT.getVectorNumElements();
12239     assert((Idx % NumElems) == 0 &&
12240            "IDX in concat is not a multiple of the result vector length.");
12241     return V->getOperand(Idx / NumElems);
12242   }
12243
12244   // Skip bitcasting
12245   if (V->getOpcode() == ISD::BITCAST)
12246     V = V.getOperand(0);
12247
12248   if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
12249     SDLoc dl(N);
12250     // Handle only simple case where vector being inserted and vector
12251     // being extracted are of same type, and are half size of larger vectors.
12252     EVT BigVT = V->getOperand(0).getValueType();
12253     EVT SmallVT = V->getOperand(1).getValueType();
12254     if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
12255       return SDValue();
12256
12257     // Only handle cases where both indexes are constants with the same type.
12258     ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
12259     ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
12260
12261     if (InsIdx && ExtIdx &&
12262         InsIdx->getValueType(0).getSizeInBits() <= 64 &&
12263         ExtIdx->getValueType(0).getSizeInBits() <= 64) {
12264       // Combine:
12265       //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
12266       // Into:
12267       //    indices are equal or bit offsets are equal => V1
12268       //    otherwise => (extract_subvec V1, ExtIdx)
12269       if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
12270           ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
12271         return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
12272       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
12273                          DAG.getNode(ISD::BITCAST, dl,
12274                                      N->getOperand(0).getValueType(),
12275                                      V->getOperand(0)), N->getOperand(1));
12276     }
12277   }
12278
12279   return SDValue();
12280 }
12281
12282 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
12283                                                  SDValue V, SelectionDAG &DAG) {
12284   SDLoc DL(V);
12285   EVT VT = V.getValueType();
12286
12287   switch (V.getOpcode()) {
12288   default:
12289     return V;
12290
12291   case ISD::CONCAT_VECTORS: {
12292     EVT OpVT = V->getOperand(0).getValueType();
12293     int OpSize = OpVT.getVectorNumElements();
12294     SmallBitVector OpUsedElements(OpSize, false);
12295     bool FoundSimplification = false;
12296     SmallVector<SDValue, 4> NewOps;
12297     NewOps.reserve(V->getNumOperands());
12298     for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
12299       SDValue Op = V->getOperand(i);
12300       bool OpUsed = false;
12301       for (int j = 0; j < OpSize; ++j)
12302         if (UsedElements[i * OpSize + j]) {
12303           OpUsedElements[j] = true;
12304           OpUsed = true;
12305         }
12306       NewOps.push_back(
12307           OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
12308                  : DAG.getUNDEF(OpVT));
12309       FoundSimplification |= Op == NewOps.back();
12310       OpUsedElements.reset();
12311     }
12312     if (FoundSimplification)
12313       V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
12314     return V;
12315   }
12316
12317   case ISD::INSERT_SUBVECTOR: {
12318     SDValue BaseV = V->getOperand(0);
12319     SDValue SubV = V->getOperand(1);
12320     auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
12321     if (!IdxN)
12322       return V;
12323
12324     int SubSize = SubV.getValueType().getVectorNumElements();
12325     int Idx = IdxN->getZExtValue();
12326     bool SubVectorUsed = false;
12327     SmallBitVector SubUsedElements(SubSize, false);
12328     for (int i = 0; i < SubSize; ++i)
12329       if (UsedElements[i + Idx]) {
12330         SubVectorUsed = true;
12331         SubUsedElements[i] = true;
12332         UsedElements[i + Idx] = false;
12333       }
12334
12335     // Now recurse on both the base and sub vectors.
12336     SDValue SimplifiedSubV =
12337         SubVectorUsed
12338             ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
12339             : DAG.getUNDEF(SubV.getValueType());
12340     SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
12341     if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
12342       V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
12343                       SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
12344     return V;
12345   }
12346   }
12347 }
12348
12349 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
12350                                        SDValue N1, SelectionDAG &DAG) {
12351   EVT VT = SVN->getValueType(0);
12352   int NumElts = VT.getVectorNumElements();
12353   SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
12354   for (int M : SVN->getMask())
12355     if (M >= 0 && M < NumElts)
12356       N0UsedElements[M] = true;
12357     else if (M >= NumElts)
12358       N1UsedElements[M - NumElts] = true;
12359
12360   SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
12361   SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
12362   if (S0 == N0 && S1 == N1)
12363     return SDValue();
12364
12365   return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
12366 }
12367
12368 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat,
12369 // or turn a shuffle of a single concat into simpler shuffle then concat.
12370 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
12371   EVT VT = N->getValueType(0);
12372   unsigned NumElts = VT.getVectorNumElements();
12373
12374   SDValue N0 = N->getOperand(0);
12375   SDValue N1 = N->getOperand(1);
12376   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
12377
12378   SmallVector<SDValue, 4> Ops;
12379   EVT ConcatVT = N0.getOperand(0).getValueType();
12380   unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
12381   unsigned NumConcats = NumElts / NumElemsPerConcat;
12382
12383   // Special case: shuffle(concat(A,B)) can be more efficiently represented
12384   // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high
12385   // half vector elements.
12386   if (NumElemsPerConcat * 2 == NumElts && N1.getOpcode() == ISD::UNDEF &&
12387       std::all_of(SVN->getMask().begin() + NumElemsPerConcat,
12388                   SVN->getMask().end(), [](int i) { return i == -1; })) {
12389     N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1),
12390                               ArrayRef<int>(SVN->getMask().begin(), NumElemsPerConcat));
12391     N1 = DAG.getUNDEF(ConcatVT);
12392     return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1);
12393   }
12394
12395   // Look at every vector that's inserted. We're looking for exact
12396   // subvector-sized copies from a concatenated vector
12397   for (unsigned I = 0; I != NumConcats; ++I) {
12398     // Make sure we're dealing with a copy.
12399     unsigned Begin = I * NumElemsPerConcat;
12400     bool AllUndef = true, NoUndef = true;
12401     for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
12402       if (SVN->getMaskElt(J) >= 0)
12403         AllUndef = false;
12404       else
12405         NoUndef = false;
12406     }
12407
12408     if (NoUndef) {
12409       if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
12410         return SDValue();
12411
12412       for (unsigned J = 1; J != NumElemsPerConcat; ++J)
12413         if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
12414           return SDValue();
12415
12416       unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
12417       if (FirstElt < N0.getNumOperands())
12418         Ops.push_back(N0.getOperand(FirstElt));
12419       else
12420         Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
12421
12422     } else if (AllUndef) {
12423       Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
12424     } else { // Mixed with general masks and undefs, can't do optimization.
12425       return SDValue();
12426     }
12427   }
12428
12429   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
12430 }
12431
12432 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
12433   EVT VT = N->getValueType(0);
12434   unsigned NumElts = VT.getVectorNumElements();
12435
12436   SDValue N0 = N->getOperand(0);
12437   SDValue N1 = N->getOperand(1);
12438
12439   assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
12440
12441   // Canonicalize shuffle undef, undef -> undef
12442   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
12443     return DAG.getUNDEF(VT);
12444
12445   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
12446
12447   // Canonicalize shuffle v, v -> v, undef
12448   if (N0 == N1) {
12449     SmallVector<int, 8> NewMask;
12450     for (unsigned i = 0; i != NumElts; ++i) {
12451       int Idx = SVN->getMaskElt(i);
12452       if (Idx >= (int)NumElts) Idx -= NumElts;
12453       NewMask.push_back(Idx);
12454     }
12455     return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
12456                                 &NewMask[0]);
12457   }
12458
12459   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
12460   if (N0.getOpcode() == ISD::UNDEF) {
12461     SmallVector<int, 8> NewMask;
12462     for (unsigned i = 0; i != NumElts; ++i) {
12463       int Idx = SVN->getMaskElt(i);
12464       if (Idx >= 0) {
12465         if (Idx >= (int)NumElts)
12466           Idx -= NumElts;
12467         else
12468           Idx = -1; // remove reference to lhs
12469       }
12470       NewMask.push_back(Idx);
12471     }
12472     return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
12473                                 &NewMask[0]);
12474   }
12475
12476   // Remove references to rhs if it is undef
12477   if (N1.getOpcode() == ISD::UNDEF) {
12478     bool Changed = false;
12479     SmallVector<int, 8> NewMask;
12480     for (unsigned i = 0; i != NumElts; ++i) {
12481       int Idx = SVN->getMaskElt(i);
12482       if (Idx >= (int)NumElts) {
12483         Idx = -1;
12484         Changed = true;
12485       }
12486       NewMask.push_back(Idx);
12487     }
12488     if (Changed)
12489       return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
12490   }
12491
12492   // If it is a splat, check if the argument vector is another splat or a
12493   // build_vector.
12494   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
12495     SDNode *V = N0.getNode();
12496
12497     // If this is a bit convert that changes the element type of the vector but
12498     // not the number of vector elements, look through it.  Be careful not to
12499     // look though conversions that change things like v4f32 to v2f64.
12500     if (V->getOpcode() == ISD::BITCAST) {
12501       SDValue ConvInput = V->getOperand(0);
12502       if (ConvInput.getValueType().isVector() &&
12503           ConvInput.getValueType().getVectorNumElements() == NumElts)
12504         V = ConvInput.getNode();
12505     }
12506
12507     if (V->getOpcode() == ISD::BUILD_VECTOR) {
12508       assert(V->getNumOperands() == NumElts &&
12509              "BUILD_VECTOR has wrong number of operands");
12510       SDValue Base;
12511       bool AllSame = true;
12512       for (unsigned i = 0; i != NumElts; ++i) {
12513         if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
12514           Base = V->getOperand(i);
12515           break;
12516         }
12517       }
12518       // Splat of <u, u, u, u>, return <u, u, u, u>
12519       if (!Base.getNode())
12520         return N0;
12521       for (unsigned i = 0; i != NumElts; ++i) {
12522         if (V->getOperand(i) != Base) {
12523           AllSame = false;
12524           break;
12525         }
12526       }
12527       // Splat of <x, x, x, x>, return <x, x, x, x>
12528       if (AllSame)
12529         return N0;
12530
12531       // Canonicalize any other splat as a build_vector.
12532       const SDValue &Splatted = V->getOperand(SVN->getSplatIndex());
12533       SmallVector<SDValue, 8> Ops(NumElts, Splatted);
12534       SDValue NewBV = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
12535                                   V->getValueType(0), Ops);
12536
12537       // We may have jumped through bitcasts, so the type of the
12538       // BUILD_VECTOR may not match the type of the shuffle.
12539       if (V->getValueType(0) != VT)
12540         NewBV = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, NewBV);
12541       return NewBV;
12542     }
12543   }
12544
12545   // There are various patterns used to build up a vector from smaller vectors,
12546   // subvectors, or elements. Scan chains of these and replace unused insertions
12547   // or components with undef.
12548   if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
12549     return S;
12550
12551   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
12552       Level < AfterLegalizeVectorOps &&
12553       (N1.getOpcode() == ISD::UNDEF ||
12554       (N1.getOpcode() == ISD::CONCAT_VECTORS &&
12555        N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
12556     SDValue V = partitionShuffleOfConcats(N, DAG);
12557
12558     if (V.getNode())
12559       return V;
12560   }
12561
12562   // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
12563   // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
12564   if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) {
12565     SmallVector<SDValue, 8> Ops;
12566     for (int M : SVN->getMask()) {
12567       SDValue Op = DAG.getUNDEF(VT.getScalarType());
12568       if (M >= 0) {
12569         int Idx = M % NumElts;
12570         SDValue &S = (M < (int)NumElts ? N0 : N1);
12571         if (S.getOpcode() == ISD::BUILD_VECTOR && S.hasOneUse()) {
12572           Op = S.getOperand(Idx);
12573         } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR && S.hasOneUse()) {
12574           if (Idx == 0)
12575             Op = S.getOperand(0);
12576         } else {
12577           // Operand can't be combined - bail out.
12578           break;
12579         }
12580       }
12581       Ops.push_back(Op);
12582     }
12583     if (Ops.size() == VT.getVectorNumElements()) {
12584       // BUILD_VECTOR requires all inputs to be of the same type, find the
12585       // maximum type and extend them all.
12586       EVT SVT = VT.getScalarType();
12587       if (SVT.isInteger())
12588         for (SDValue &Op : Ops)
12589           SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
12590       if (SVT != VT.getScalarType())
12591         for (SDValue &Op : Ops)
12592           Op = TLI.isZExtFree(Op.getValueType(), SVT)
12593                    ? DAG.getZExtOrTrunc(Op, SDLoc(N), SVT)
12594                    : DAG.getSExtOrTrunc(Op, SDLoc(N), SVT);
12595       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Ops);
12596     }
12597   }
12598
12599   // If this shuffle only has a single input that is a bitcasted shuffle,
12600   // attempt to merge the 2 shuffles and suitably bitcast the inputs/output
12601   // back to their original types.
12602   if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
12603       N1.getOpcode() == ISD::UNDEF && Level < AfterLegalizeVectorOps &&
12604       TLI.isTypeLegal(VT)) {
12605
12606     // Peek through the bitcast only if there is one user.
12607     SDValue BC0 = N0;
12608     while (BC0.getOpcode() == ISD::BITCAST) {
12609       if (!BC0.hasOneUse())
12610         break;
12611       BC0 = BC0.getOperand(0);
12612     }
12613
12614     auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) {
12615       if (Scale == 1)
12616         return SmallVector<int, 8>(Mask.begin(), Mask.end());
12617
12618       SmallVector<int, 8> NewMask;
12619       for (int M : Mask)
12620         for (int s = 0; s != Scale; ++s)
12621           NewMask.push_back(M < 0 ? -1 : Scale * M + s);
12622       return NewMask;
12623     };
12624
12625     if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) {
12626       EVT SVT = VT.getScalarType();
12627       EVT InnerVT = BC0->getValueType(0);
12628       EVT InnerSVT = InnerVT.getScalarType();
12629
12630       // Determine which shuffle works with the smaller scalar type.
12631       EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT;
12632       EVT ScaleSVT = ScaleVT.getScalarType();
12633
12634       if (TLI.isTypeLegal(ScaleVT) &&
12635           0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) &&
12636           0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) {
12637
12638         int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits();
12639         int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits();
12640
12641         // Scale the shuffle masks to the smaller scalar type.
12642         ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0);
12643         SmallVector<int, 8> InnerMask =
12644             ScaleShuffleMask(InnerSVN->getMask(), InnerScale);
12645         SmallVector<int, 8> OuterMask =
12646             ScaleShuffleMask(SVN->getMask(), OuterScale);
12647
12648         // Merge the shuffle masks.
12649         SmallVector<int, 8> NewMask;
12650         for (int M : OuterMask)
12651           NewMask.push_back(M < 0 ? -1 : InnerMask[M]);
12652
12653         // Test for shuffle mask legality over both commutations.
12654         SDValue SV0 = BC0->getOperand(0);
12655         SDValue SV1 = BC0->getOperand(1);
12656         bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
12657         if (!LegalMask) {
12658           std::swap(SV0, SV1);
12659           ShuffleVectorSDNode::commuteMask(NewMask);
12660           LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
12661         }
12662
12663         if (LegalMask) {
12664           SV0 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV0);
12665           SV1 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV1);
12666           return DAG.getNode(
12667               ISD::BITCAST, SDLoc(N), VT,
12668               DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask));
12669         }
12670       }
12671     }
12672   }
12673
12674   // Canonicalize shuffles according to rules:
12675   //  shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
12676   //  shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
12677   //  shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
12678   if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
12679       N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
12680       TLI.isTypeLegal(VT)) {
12681     // The incoming shuffle must be of the same type as the result of the
12682     // current shuffle.
12683     assert(N1->getOperand(0).getValueType() == VT &&
12684            "Shuffle types don't match");
12685
12686     SDValue SV0 = N1->getOperand(0);
12687     SDValue SV1 = N1->getOperand(1);
12688     bool HasSameOp0 = N0 == SV0;
12689     bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
12690     if (HasSameOp0 || IsSV1Undef || N0 == SV1)
12691       // Commute the operands of this shuffle so that next rule
12692       // will trigger.
12693       return DAG.getCommutedVectorShuffle(*SVN);
12694   }
12695
12696   // Try to fold according to rules:
12697   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
12698   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
12699   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
12700   // Don't try to fold shuffles with illegal type.
12701   // Only fold if this shuffle is the only user of the other shuffle.
12702   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) &&
12703       Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) {
12704     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
12705
12706     // The incoming shuffle must be of the same type as the result of the
12707     // current shuffle.
12708     assert(OtherSV->getOperand(0).getValueType() == VT &&
12709            "Shuffle types don't match");
12710
12711     SDValue SV0, SV1;
12712     SmallVector<int, 4> Mask;
12713     // Compute the combined shuffle mask for a shuffle with SV0 as the first
12714     // operand, and SV1 as the second operand.
12715     for (unsigned i = 0; i != NumElts; ++i) {
12716       int Idx = SVN->getMaskElt(i);
12717       if (Idx < 0) {
12718         // Propagate Undef.
12719         Mask.push_back(Idx);
12720         continue;
12721       }
12722
12723       SDValue CurrentVec;
12724       if (Idx < (int)NumElts) {
12725         // This shuffle index refers to the inner shuffle N0. Lookup the inner
12726         // shuffle mask to identify which vector is actually referenced.
12727         Idx = OtherSV->getMaskElt(Idx);
12728         if (Idx < 0) {
12729           // Propagate Undef.
12730           Mask.push_back(Idx);
12731           continue;
12732         }
12733
12734         CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
12735                                            : OtherSV->getOperand(1);
12736       } else {
12737         // This shuffle index references an element within N1.
12738         CurrentVec = N1;
12739       }
12740
12741       // Simple case where 'CurrentVec' is UNDEF.
12742       if (CurrentVec.getOpcode() == ISD::UNDEF) {
12743         Mask.push_back(-1);
12744         continue;
12745       }
12746
12747       // Canonicalize the shuffle index. We don't know yet if CurrentVec
12748       // will be the first or second operand of the combined shuffle.
12749       Idx = Idx % NumElts;
12750       if (!SV0.getNode() || SV0 == CurrentVec) {
12751         // Ok. CurrentVec is the left hand side.
12752         // Update the mask accordingly.
12753         SV0 = CurrentVec;
12754         Mask.push_back(Idx);
12755         continue;
12756       }
12757
12758       // Bail out if we cannot convert the shuffle pair into a single shuffle.
12759       if (SV1.getNode() && SV1 != CurrentVec)
12760         return SDValue();
12761
12762       // Ok. CurrentVec is the right hand side.
12763       // Update the mask accordingly.
12764       SV1 = CurrentVec;
12765       Mask.push_back(Idx + NumElts);
12766     }
12767
12768     // Check if all indices in Mask are Undef. In case, propagate Undef.
12769     bool isUndefMask = true;
12770     for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
12771       isUndefMask &= Mask[i] < 0;
12772
12773     if (isUndefMask)
12774       return DAG.getUNDEF(VT);
12775
12776     if (!SV0.getNode())
12777       SV0 = DAG.getUNDEF(VT);
12778     if (!SV1.getNode())
12779       SV1 = DAG.getUNDEF(VT);
12780
12781     // Avoid introducing shuffles with illegal mask.
12782     if (!TLI.isShuffleMaskLegal(Mask, VT)) {
12783       ShuffleVectorSDNode::commuteMask(Mask);
12784
12785       if (!TLI.isShuffleMaskLegal(Mask, VT))
12786         return SDValue();
12787
12788       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
12789       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
12790       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
12791       std::swap(SV0, SV1);
12792     }
12793
12794     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
12795     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
12796     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
12797     return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
12798   }
12799
12800   return SDValue();
12801 }
12802
12803 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) {
12804   SDValue InVal = N->getOperand(0);
12805   EVT VT = N->getValueType(0);
12806
12807   // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern
12808   // with a VECTOR_SHUFFLE.
12809   if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
12810     SDValue InVec = InVal->getOperand(0);
12811     SDValue EltNo = InVal->getOperand(1);
12812
12813     // FIXME: We could support implicit truncation if the shuffle can be
12814     // scaled to a smaller vector scalar type.
12815     ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo);
12816     if (C0 && VT == InVec.getValueType() &&
12817         VT.getScalarType() == InVal.getValueType()) {
12818       SmallVector<int, 8> NewMask(VT.getVectorNumElements(), -1);
12819       int Elt = C0->getZExtValue();
12820       NewMask[0] = Elt;
12821
12822       if (TLI.isShuffleMaskLegal(NewMask, VT))
12823         return DAG.getVectorShuffle(VT, SDLoc(N), InVec, DAG.getUNDEF(VT),
12824                                     NewMask);
12825     }
12826   }
12827
12828   return SDValue();
12829 }
12830
12831 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
12832   SDValue N0 = N->getOperand(0);
12833   SDValue N2 = N->getOperand(2);
12834
12835   // If the input vector is a concatenation, and the insert replaces
12836   // one of the halves, we can optimize into a single concat_vectors.
12837   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
12838       N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
12839     APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
12840     EVT VT = N->getValueType(0);
12841
12842     // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
12843     // (concat_vectors Z, Y)
12844     if (InsIdx == 0)
12845       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
12846                          N->getOperand(1), N0.getOperand(1));
12847
12848     // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
12849     // (concat_vectors X, Z)
12850     if (InsIdx == VT.getVectorNumElements()/2)
12851       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
12852                          N0.getOperand(0), N->getOperand(1));
12853   }
12854
12855   return SDValue();
12856 }
12857
12858 SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) {
12859   SDValue N0 = N->getOperand(0);
12860
12861   // fold (fp_to_fp16 (fp16_to_fp op)) -> op
12862   if (N0->getOpcode() == ISD::FP16_TO_FP)
12863     return N0->getOperand(0);
12864
12865   return SDValue();
12866 }
12867
12868 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
12869 /// with the destination vector and a zero vector.
12870 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
12871 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
12872 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
12873   EVT VT = N->getValueType(0);
12874   SDValue LHS = N->getOperand(0);
12875   SDValue RHS = N->getOperand(1);
12876   SDLoc dl(N);
12877
12878   // Make sure we're not running after operation legalization where it 
12879   // may have custom lowered the vector shuffles.
12880   if (LegalOperations)
12881     return SDValue();
12882
12883   if (N->getOpcode() != ISD::AND)
12884     return SDValue();
12885
12886   if (RHS.getOpcode() == ISD::BITCAST)
12887     RHS = RHS.getOperand(0);
12888
12889   if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
12890     SmallVector<int, 8> Indices;
12891     unsigned NumElts = RHS.getNumOperands();
12892
12893     for (unsigned i = 0; i != NumElts; ++i) {
12894       SDValue Elt = RHS.getOperand(i);
12895       if (const ConstantSDNode *EltC = dyn_cast<const ConstantSDNode>(Elt)) {
12896         if (EltC->isAllOnesValue())
12897           Indices.push_back(i);
12898         else if (EltC->isNullValue())
12899           Indices.push_back(NumElts+i);
12900         else
12901           return SDValue();
12902       } else {
12903         return SDValue();
12904       }
12905     }
12906
12907     // Let's see if the target supports this vector_shuffle.
12908     EVT RVT = RHS.getValueType();
12909     if (!TLI.isVectorClearMaskLegal(Indices, RVT))
12910       return SDValue();
12911
12912     // Return the new VECTOR_SHUFFLE node.
12913     EVT EltVT = RVT.getVectorElementType();
12914     SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
12915                                    DAG.getConstant(0, dl, EltVT));
12916     SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, dl, RVT, ZeroOps);
12917     LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
12918     SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
12919     return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
12920   }
12921
12922   return SDValue();
12923 }
12924
12925 /// Visit a binary vector operation, like ADD.
12926 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
12927   assert(N->getValueType(0).isVector() &&
12928          "SimplifyVBinOp only works on vectors!");
12929
12930   SDValue LHS = N->getOperand(0);
12931   SDValue RHS = N->getOperand(1);
12932
12933   if (SDValue Shuffle = XformToShuffleWithZero(N))
12934     return Shuffle;
12935
12936   // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
12937   // this operation.
12938   if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
12939       RHS.getOpcode() == ISD::BUILD_VECTOR) {
12940     // Check if both vectors are constants. If not bail out.
12941     if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
12942           cast<BuildVectorSDNode>(RHS)->isConstant()))
12943       return SDValue();
12944
12945     SmallVector<SDValue, 8> Ops;
12946     for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
12947       SDValue LHSOp = LHS.getOperand(i);
12948       SDValue RHSOp = RHS.getOperand(i);
12949
12950       // Can't fold divide by zero.
12951       if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
12952           N->getOpcode() == ISD::FDIV) {
12953         if (isNullConstant(RHSOp) || (RHSOp.getOpcode() == ISD::ConstantFP &&
12954              cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
12955           break;
12956       }
12957
12958       EVT VT = LHSOp.getValueType();
12959       EVT RVT = RHSOp.getValueType();
12960       if (RVT != VT) {
12961         // Integer BUILD_VECTOR operands may have types larger than the element
12962         // size (e.g., when the element type is not legal).  Prior to type
12963         // legalization, the types may not match between the two BUILD_VECTORS.
12964         // Truncate one of the operands to make them match.
12965         if (RVT.getSizeInBits() > VT.getSizeInBits()) {
12966           RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
12967         } else {
12968           LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
12969           VT = RVT;
12970         }
12971       }
12972       SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
12973                                    LHSOp, RHSOp);
12974       if (FoldOp.getOpcode() != ISD::UNDEF &&
12975           FoldOp.getOpcode() != ISD::Constant &&
12976           FoldOp.getOpcode() != ISD::ConstantFP)
12977         break;
12978       Ops.push_back(FoldOp);
12979       AddToWorklist(FoldOp.getNode());
12980     }
12981
12982     if (Ops.size() == LHS.getNumOperands())
12983       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
12984   }
12985
12986   // Type legalization might introduce new shuffles in the DAG.
12987   // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
12988   //   -> (shuffle (VBinOp (A, B)), Undef, Mask).
12989   if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
12990       isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
12991       LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
12992       RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
12993     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
12994     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
12995
12996     if (SVN0->getMask().equals(SVN1->getMask())) {
12997       EVT VT = N->getValueType(0);
12998       SDValue UndefVector = LHS.getOperand(1);
12999       SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
13000                                      LHS.getOperand(0), RHS.getOperand(0));
13001       AddUsersToWorklist(N);
13002       return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
13003                                   &SVN0->getMask()[0]);
13004     }
13005   }
13006
13007   return SDValue();
13008 }
13009
13010 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
13011                                     SDValue N1, SDValue N2){
13012   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
13013
13014   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
13015                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
13016
13017   // If we got a simplified select_cc node back from SimplifySelectCC, then
13018   // break it down into a new SETCC node, and a new SELECT node, and then return
13019   // the SELECT node, since we were called with a SELECT node.
13020   if (SCC.getNode()) {
13021     // Check to see if we got a select_cc back (to turn into setcc/select).
13022     // Otherwise, just return whatever node we got back, like fabs.
13023     if (SCC.getOpcode() == ISD::SELECT_CC) {
13024       SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
13025                                   N0.getValueType(),
13026                                   SCC.getOperand(0), SCC.getOperand(1),
13027                                   SCC.getOperand(4));
13028       AddToWorklist(SETCC.getNode());
13029       return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
13030                            SCC.getOperand(2), SCC.getOperand(3));
13031     }
13032
13033     return SCC;
13034   }
13035   return SDValue();
13036 }
13037
13038 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
13039 /// being selected between, see if we can simplify the select.  Callers of this
13040 /// should assume that TheSelect is deleted if this returns true.  As such, they
13041 /// should return the appropriate thing (e.g. the node) back to the top-level of
13042 /// the DAG combiner loop to avoid it being looked at.
13043 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
13044                                     SDValue RHS) {
13045
13046   // fold (select (setcc x, -0.0, *lt), NaN, (fsqrt x))
13047   // The select + setcc is redundant, because fsqrt returns NaN for X < -0.
13048   if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) {
13049     if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) {
13050       // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?))
13051       SDValue Sqrt = RHS;
13052       ISD::CondCode CC;
13053       SDValue CmpLHS;
13054       const ConstantFPSDNode *NegZero = nullptr;
13055
13056       if (TheSelect->getOpcode() == ISD::SELECT_CC) {
13057         CC = dyn_cast<CondCodeSDNode>(TheSelect->getOperand(4))->get();
13058         CmpLHS = TheSelect->getOperand(0);
13059         NegZero = isConstOrConstSplatFP(TheSelect->getOperand(1));
13060       } else {
13061         // SELECT or VSELECT
13062         SDValue Cmp = TheSelect->getOperand(0);
13063         if (Cmp.getOpcode() == ISD::SETCC) {
13064           CC = dyn_cast<CondCodeSDNode>(Cmp.getOperand(2))->get();
13065           CmpLHS = Cmp.getOperand(0);
13066           NegZero = isConstOrConstSplatFP(Cmp.getOperand(1));
13067         }
13068       }
13069       if (NegZero && NegZero->isNegative() && NegZero->isZero() &&
13070           Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT ||
13071           CC == ISD::SETULT || CC == ISD::SETLT)) {
13072         // We have: (select (setcc x, -0.0, *lt), NaN, (fsqrt x))
13073         CombineTo(TheSelect, Sqrt);
13074         return true;
13075       }
13076     }
13077   }
13078   // Cannot simplify select with vector condition
13079   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
13080
13081   // If this is a select from two identical things, try to pull the operation
13082   // through the select.
13083   if (LHS.getOpcode() != RHS.getOpcode() ||
13084       !LHS.hasOneUse() || !RHS.hasOneUse())
13085     return false;
13086
13087   // If this is a load and the token chain is identical, replace the select
13088   // of two loads with a load through a select of the address to load from.
13089   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
13090   // constants have been dropped into the constant pool.
13091   if (LHS.getOpcode() == ISD::LOAD) {
13092     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
13093     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
13094
13095     // Token chains must be identical.
13096     if (LHS.getOperand(0) != RHS.getOperand(0) ||
13097         // Do not let this transformation reduce the number of volatile loads.
13098         LLD->isVolatile() || RLD->isVolatile() ||
13099         // FIXME: If either is a pre/post inc/dec load,
13100         // we'd need to split out the address adjustment.
13101         LLD->isIndexed() || RLD->isIndexed() ||
13102         // If this is an EXTLOAD, the VT's must match.
13103         LLD->getMemoryVT() != RLD->getMemoryVT() ||
13104         // If this is an EXTLOAD, the kind of extension must match.
13105         (LLD->getExtensionType() != RLD->getExtensionType() &&
13106          // The only exception is if one of the extensions is anyext.
13107          LLD->getExtensionType() != ISD::EXTLOAD &&
13108          RLD->getExtensionType() != ISD::EXTLOAD) ||
13109         // FIXME: this discards src value information.  This is
13110         // over-conservative. It would be beneficial to be able to remember
13111         // both potential memory locations.  Since we are discarding
13112         // src value info, don't do the transformation if the memory
13113         // locations are not in the default address space.
13114         LLD->getPointerInfo().getAddrSpace() != 0 ||
13115         RLD->getPointerInfo().getAddrSpace() != 0 ||
13116         !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
13117                                       LLD->getBasePtr().getValueType()))
13118       return false;
13119
13120     // Check that the select condition doesn't reach either load.  If so,
13121     // folding this will induce a cycle into the DAG.  If not, this is safe to
13122     // xform, so create a select of the addresses.
13123     SDValue Addr;
13124     if (TheSelect->getOpcode() == ISD::SELECT) {
13125       SDNode *CondNode = TheSelect->getOperand(0).getNode();
13126       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
13127           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
13128         return false;
13129       // The loads must not depend on one another.
13130       if (LLD->isPredecessorOf(RLD) ||
13131           RLD->isPredecessorOf(LLD))
13132         return false;
13133       Addr = DAG.getSelect(SDLoc(TheSelect),
13134                            LLD->getBasePtr().getValueType(),
13135                            TheSelect->getOperand(0), LLD->getBasePtr(),
13136                            RLD->getBasePtr());
13137     } else {  // Otherwise SELECT_CC
13138       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
13139       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
13140
13141       if ((LLD->hasAnyUseOfValue(1) &&
13142            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
13143           (RLD->hasAnyUseOfValue(1) &&
13144            (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
13145         return false;
13146
13147       Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
13148                          LLD->getBasePtr().getValueType(),
13149                          TheSelect->getOperand(0),
13150                          TheSelect->getOperand(1),
13151                          LLD->getBasePtr(), RLD->getBasePtr(),
13152                          TheSelect->getOperand(4));
13153     }
13154
13155     SDValue Load;
13156     // It is safe to replace the two loads if they have different alignments,
13157     // but the new load must be the minimum (most restrictive) alignment of the
13158     // inputs.
13159     bool isInvariant = LLD->isInvariant() & RLD->isInvariant();
13160     unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
13161     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
13162       Load = DAG.getLoad(TheSelect->getValueType(0),
13163                          SDLoc(TheSelect),
13164                          // FIXME: Discards pointer and AA info.
13165                          LLD->getChain(), Addr, MachinePointerInfo(),
13166                          LLD->isVolatile(), LLD->isNonTemporal(),
13167                          isInvariant, Alignment);
13168     } else {
13169       Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
13170                             RLD->getExtensionType() : LLD->getExtensionType(),
13171                             SDLoc(TheSelect),
13172                             TheSelect->getValueType(0),
13173                             // FIXME: Discards pointer and AA info.
13174                             LLD->getChain(), Addr, MachinePointerInfo(),
13175                             LLD->getMemoryVT(), LLD->isVolatile(),
13176                             LLD->isNonTemporal(), isInvariant, Alignment);
13177     }
13178
13179     // Users of the select now use the result of the load.
13180     CombineTo(TheSelect, Load);
13181
13182     // Users of the old loads now use the new load's chain.  We know the
13183     // old-load value is dead now.
13184     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
13185     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
13186     return true;
13187   }
13188
13189   return false;
13190 }
13191
13192 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
13193 /// where 'cond' is the comparison specified by CC.
13194 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
13195                                       SDValue N2, SDValue N3,
13196                                       ISD::CondCode CC, bool NotExtCompare) {
13197   // (x ? y : y) -> y.
13198   if (N2 == N3) return N2;
13199
13200   EVT VT = N2.getValueType();
13201   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
13202   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
13203
13204   // Determine if the condition we're dealing with is constant
13205   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
13206                               N0, N1, CC, DL, false);
13207   if (SCC.getNode()) AddToWorklist(SCC.getNode());
13208
13209   if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) {
13210     // fold select_cc true, x, y -> x
13211     // fold select_cc false, x, y -> y
13212     return !SCCC->isNullValue() ? N2 : N3;
13213   }
13214
13215   // Check to see if we can simplify the select into an fabs node
13216   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
13217     // Allow either -0.0 or 0.0
13218     if (CFP->getValueAPF().isZero()) {
13219       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
13220       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
13221           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
13222           N2 == N3.getOperand(0))
13223         return DAG.getNode(ISD::FABS, DL, VT, N0);
13224
13225       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
13226       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
13227           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
13228           N2.getOperand(0) == N3)
13229         return DAG.getNode(ISD::FABS, DL, VT, N3);
13230     }
13231   }
13232
13233   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
13234   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
13235   // in it.  This is a win when the constant is not otherwise available because
13236   // it replaces two constant pool loads with one.  We only do this if the FP
13237   // type is known to be legal, because if it isn't, then we are before legalize
13238   // types an we want the other legalization to happen first (e.g. to avoid
13239   // messing with soft float) and if the ConstantFP is not legal, because if
13240   // it is legal, we may not need to store the FP constant in a constant pool.
13241   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
13242     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
13243       if (TLI.isTypeLegal(N2.getValueType()) &&
13244           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
13245                TargetLowering::Legal &&
13246            !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
13247            !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
13248           // If both constants have multiple uses, then we won't need to do an
13249           // extra load, they are likely around in registers for other users.
13250           (TV->hasOneUse() || FV->hasOneUse())) {
13251         Constant *Elts[] = {
13252           const_cast<ConstantFP*>(FV->getConstantFPValue()),
13253           const_cast<ConstantFP*>(TV->getConstantFPValue())
13254         };
13255         Type *FPTy = Elts[0]->getType();
13256         const DataLayout &TD = *TLI.getDataLayout();
13257
13258         // Create a ConstantArray of the two constants.
13259         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
13260         SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
13261                                             TD.getPrefTypeAlignment(FPTy));
13262         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
13263
13264         // Get the offsets to the 0 and 1 element of the array so that we can
13265         // select between them.
13266         SDValue Zero = DAG.getIntPtrConstant(0, DL);
13267         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
13268         SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV));
13269
13270         SDValue Cond = DAG.getSetCC(DL,
13271                                     getSetCCResultType(N0.getValueType()),
13272                                     N0, N1, CC);
13273         AddToWorklist(Cond.getNode());
13274         SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
13275                                           Cond, One, Zero);
13276         AddToWorklist(CstOffset.getNode());
13277         CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
13278                             CstOffset);
13279         AddToWorklist(CPIdx.getNode());
13280         return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
13281                            MachinePointerInfo::getConstantPool(), false,
13282                            false, false, Alignment);
13283       }
13284     }
13285
13286   // Check to see if we can perform the "gzip trick", transforming
13287   // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
13288   if (N1C && isNullConstant(N3) && CC == ISD::SETLT &&
13289       (N1C->isNullValue() ||                         // (a < 0) ? b : 0
13290        (N1C->getAPIntValue() == 1 && N0 == N2))) {   // (a < 1) ? a : 0
13291     EVT XType = N0.getValueType();
13292     EVT AType = N2.getValueType();
13293     if (XType.bitsGE(AType)) {
13294       // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
13295       // single-bit constant.
13296       if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) {
13297         unsigned ShCtV = N2C->getAPIntValue().logBase2();
13298         ShCtV = XType.getSizeInBits() - ShCtV - 1;
13299         SDValue ShCt = DAG.getConstant(ShCtV, SDLoc(N0),
13300                                        getShiftAmountTy(N0.getValueType()));
13301         SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
13302                                     XType, N0, ShCt);
13303         AddToWorklist(Shift.getNode());
13304
13305         if (XType.bitsGT(AType)) {
13306           Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
13307           AddToWorklist(Shift.getNode());
13308         }
13309
13310         return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
13311       }
13312
13313       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
13314                                   XType, N0,
13315                                   DAG.getConstant(XType.getSizeInBits() - 1,
13316                                                   SDLoc(N0),
13317                                          getShiftAmountTy(N0.getValueType())));
13318       AddToWorklist(Shift.getNode());
13319
13320       if (XType.bitsGT(AType)) {
13321         Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
13322         AddToWorklist(Shift.getNode());
13323       }
13324
13325       return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
13326     }
13327   }
13328
13329   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
13330   // where y is has a single bit set.
13331   // A plaintext description would be, we can turn the SELECT_CC into an AND
13332   // when the condition can be materialized as an all-ones register.  Any
13333   // single bit-test can be materialized as an all-ones register with
13334   // shift-left and shift-right-arith.
13335   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
13336       N0->getValueType(0) == VT && isNullConstant(N1) && isNullConstant(N2)) {
13337     SDValue AndLHS = N0->getOperand(0);
13338     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
13339     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
13340       // Shift the tested bit over the sign bit.
13341       APInt AndMask = ConstAndRHS->getAPIntValue();
13342       SDValue ShlAmt =
13343         DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS),
13344                         getShiftAmountTy(AndLHS.getValueType()));
13345       SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
13346
13347       // Now arithmetic right shift it all the way over, so the result is either
13348       // all-ones, or zero.
13349       SDValue ShrAmt =
13350         DAG.getConstant(AndMask.getBitWidth() - 1, SDLoc(Shl),
13351                         getShiftAmountTy(Shl.getValueType()));
13352       SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
13353
13354       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
13355     }
13356   }
13357
13358   // fold select C, 16, 0 -> shl C, 4
13359   if (N2C && isNullConstant(N3) && N2C->getAPIntValue().isPowerOf2() &&
13360       TLI.getBooleanContents(N0.getValueType()) ==
13361           TargetLowering::ZeroOrOneBooleanContent) {
13362
13363     // If the caller doesn't want us to simplify this into a zext of a compare,
13364     // don't do it.
13365     if (NotExtCompare && N2C->getAPIntValue() == 1)
13366       return SDValue();
13367
13368     // Get a SetCC of the condition
13369     // NOTE: Don't create a SETCC if it's not legal on this target.
13370     if (!LegalOperations ||
13371         TLI.isOperationLegal(ISD::SETCC,
13372           LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
13373       SDValue Temp, SCC;
13374       // cast from setcc result type to select result type
13375       if (LegalTypes) {
13376         SCC  = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
13377                             N0, N1, CC);
13378         if (N2.getValueType().bitsLT(SCC.getValueType()))
13379           Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
13380                                         N2.getValueType());
13381         else
13382           Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
13383                              N2.getValueType(), SCC);
13384       } else {
13385         SCC  = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
13386         Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
13387                            N2.getValueType(), SCC);
13388       }
13389
13390       AddToWorklist(SCC.getNode());
13391       AddToWorklist(Temp.getNode());
13392
13393       if (N2C->getAPIntValue() == 1)
13394         return Temp;
13395
13396       // shl setcc result by log2 n2c
13397       return DAG.getNode(
13398           ISD::SHL, DL, N2.getValueType(), Temp,
13399           DAG.getConstant(N2C->getAPIntValue().logBase2(), SDLoc(Temp),
13400                           getShiftAmountTy(Temp.getValueType())));
13401     }
13402   }
13403
13404   // Check to see if this is the equivalent of setcc
13405   // FIXME: Turn all of these into setcc if setcc if setcc is legal
13406   // otherwise, go ahead with the folds.
13407   if (0 && isNullConstant(N3) && N2C && (N2C->getAPIntValue() == 1ULL)) {
13408     EVT XType = N0.getValueType();
13409     if (!LegalOperations ||
13410         TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
13411       SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
13412       if (Res.getValueType() != VT)
13413         Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
13414       return Res;
13415     }
13416
13417     // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
13418     if (isNullConstant(N1) && CC == ISD::SETEQ &&
13419         (!LegalOperations ||
13420          TLI.isOperationLegal(ISD::CTLZ, XType))) {
13421       SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
13422       return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
13423                          DAG.getConstant(Log2_32(XType.getSizeInBits()),
13424                                          SDLoc(Ctlz),
13425                                        getShiftAmountTy(Ctlz.getValueType())));
13426     }
13427     // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
13428     if (isNullConstant(N1) && CC == ISD::SETGT) {
13429       SDLoc DL(N0);
13430       SDValue NegN0 = DAG.getNode(ISD::SUB, DL,
13431                                   XType, DAG.getConstant(0, DL, XType), N0);
13432       SDValue NotN0 = DAG.getNOT(DL, N0, XType);
13433       return DAG.getNode(ISD::SRL, DL, XType,
13434                          DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
13435                          DAG.getConstant(XType.getSizeInBits() - 1, DL,
13436                                          getShiftAmountTy(XType)));
13437     }
13438     // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
13439     if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
13440       SDLoc DL(N0);
13441       SDValue Sign = DAG.getNode(ISD::SRL, DL, XType, N0,
13442                                  DAG.getConstant(XType.getSizeInBits() - 1, DL,
13443                                          getShiftAmountTy(N0.getValueType())));
13444       return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, DL,
13445                                                                     XType));
13446     }
13447   }
13448
13449   // Check to see if this is an integer abs.
13450   // select_cc setg[te] X,  0,  X, -X ->
13451   // select_cc setgt    X, -1,  X, -X ->
13452   // select_cc setl[te] X,  0, -X,  X ->
13453   // select_cc setlt    X,  1, -X,  X ->
13454   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
13455   if (N1C) {
13456     ConstantSDNode *SubC = nullptr;
13457     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
13458          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
13459         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
13460       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
13461     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
13462               (N1C->isOne() && CC == ISD::SETLT)) &&
13463              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
13464       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
13465
13466     EVT XType = N0.getValueType();
13467     if (SubC && SubC->isNullValue() && XType.isInteger()) {
13468       SDLoc DL(N0);
13469       SDValue Shift = DAG.getNode(ISD::SRA, DL, XType,
13470                                   N0,
13471                                   DAG.getConstant(XType.getSizeInBits() - 1, DL,
13472                                          getShiftAmountTy(N0.getValueType())));
13473       SDValue Add = DAG.getNode(ISD::ADD, DL,
13474                                 XType, N0, Shift);
13475       AddToWorklist(Shift.getNode());
13476       AddToWorklist(Add.getNode());
13477       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
13478     }
13479   }
13480
13481   return SDValue();
13482 }
13483
13484 /// This is a stub for TargetLowering::SimplifySetCC.
13485 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
13486                                    SDValue N1, ISD::CondCode Cond,
13487                                    SDLoc DL, bool foldBooleans) {
13488   TargetLowering::DAGCombinerInfo
13489     DagCombineInfo(DAG, Level, false, this);
13490   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
13491 }
13492
13493 /// Given an ISD::SDIV node expressing a divide by constant, return
13494 /// a DAG expression to select that will generate the same value by multiplying
13495 /// by a magic number.
13496 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
13497 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
13498   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13499   if (!C)
13500     return SDValue();
13501
13502   // Avoid division by zero.
13503   if (C->isNullValue())
13504     return SDValue();
13505
13506   std::vector<SDNode*> Built;
13507   SDValue S =
13508       TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
13509
13510   for (SDNode *N : Built)
13511     AddToWorklist(N);
13512   return S;
13513 }
13514
13515 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
13516 /// DAG expression that will generate the same value by right shifting.
13517 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
13518   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13519   if (!C)
13520     return SDValue();
13521
13522   // Avoid division by zero.
13523   if (C->isNullValue())
13524     return SDValue();
13525
13526   std::vector<SDNode *> Built;
13527   SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
13528
13529   for (SDNode *N : Built)
13530     AddToWorklist(N);
13531   return S;
13532 }
13533
13534 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
13535 /// expression that will generate the same value by multiplying by a magic
13536 /// number.
13537 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
13538 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
13539   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13540   if (!C)
13541     return SDValue();
13542
13543   // Avoid division by zero.
13544   if (C->isNullValue())
13545     return SDValue();
13546
13547   std::vector<SDNode*> Built;
13548   SDValue S =
13549       TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
13550
13551   for (SDNode *N : Built)
13552     AddToWorklist(N);
13553   return S;
13554 }
13555
13556 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op) {
13557   if (Level >= AfterLegalizeDAG)
13558     return SDValue();
13559
13560   // Expose the DAG combiner to the target combiner implementations.
13561   TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
13562
13563   unsigned Iterations = 0;
13564   if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) {
13565     if (Iterations) {
13566       // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13567       // For the reciprocal, we need to find the zero of the function:
13568       //   F(X) = A X - 1 [which has a zero at X = 1/A]
13569       //     =>
13570       //   X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
13571       //     does not require additional intermediate precision]
13572       EVT VT = Op.getValueType();
13573       SDLoc DL(Op);
13574       SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
13575
13576       AddToWorklist(Est.getNode());
13577
13578       // Newton iterations: Est = Est + Est (1 - Arg * Est)
13579       for (unsigned i = 0; i < Iterations; ++i) {
13580         SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est);
13581         AddToWorklist(NewEst.getNode());
13582
13583         NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst);
13584         AddToWorklist(NewEst.getNode());
13585
13586         NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
13587         AddToWorklist(NewEst.getNode());
13588
13589         Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst);
13590         AddToWorklist(Est.getNode());
13591       }
13592     }
13593     return Est;
13594   }
13595
13596   return SDValue();
13597 }
13598
13599 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13600 /// For the reciprocal sqrt, we need to find the zero of the function:
13601 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
13602 ///     =>
13603 ///   X_{i+1} = X_i (1.5 - A X_i^2 / 2)
13604 /// As a result, we precompute A/2 prior to the iteration loop.
13605 SDValue DAGCombiner::BuildRsqrtNROneConst(SDValue Arg, SDValue Est,
13606                                           unsigned Iterations) {
13607   EVT VT = Arg.getValueType();
13608   SDLoc DL(Arg);
13609   SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT);
13610
13611   // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
13612   // this entire sequence requires only one FP constant.
13613   SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg);
13614   AddToWorklist(HalfArg.getNode());
13615
13616   HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg);
13617   AddToWorklist(HalfArg.getNode());
13618
13619   // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
13620   for (unsigned i = 0; i < Iterations; ++i) {
13621     SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
13622     AddToWorklist(NewEst.getNode());
13623
13624     NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst);
13625     AddToWorklist(NewEst.getNode());
13626
13627     NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst);
13628     AddToWorklist(NewEst.getNode());
13629
13630     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
13631     AddToWorklist(Est.getNode());
13632   }
13633   return Est;
13634 }
13635
13636 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13637 /// For the reciprocal sqrt, we need to find the zero of the function:
13638 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
13639 ///     =>
13640 ///   X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
13641 SDValue DAGCombiner::BuildRsqrtNRTwoConst(SDValue Arg, SDValue Est,
13642                                           unsigned Iterations) {
13643   EVT VT = Arg.getValueType();
13644   SDLoc DL(Arg);
13645   SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT);
13646   SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT);
13647
13648   // Newton iterations: Est = -0.5 * Est * (-3.0 + Arg * Est * Est)
13649   for (unsigned i = 0; i < Iterations; ++i) {
13650     SDValue HalfEst = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf);
13651     AddToWorklist(HalfEst.getNode());
13652
13653     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
13654     AddToWorklist(Est.getNode());
13655
13656     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg);
13657     AddToWorklist(Est.getNode());
13658
13659     Est = DAG.getNode(ISD::FADD, DL, VT, Est, MinusThree);
13660     AddToWorklist(Est.getNode());
13661
13662     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, HalfEst);
13663     AddToWorklist(Est.getNode());
13664   }
13665   return Est;
13666 }
13667
13668 SDValue DAGCombiner::BuildRsqrtEstimate(SDValue Op) {
13669   if (Level >= AfterLegalizeDAG)
13670     return SDValue();
13671
13672   // Expose the DAG combiner to the target combiner implementations.
13673   TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
13674   unsigned Iterations = 0;
13675   bool UseOneConstNR = false;
13676   if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations, UseOneConstNR)) {
13677     AddToWorklist(Est.getNode());
13678     if (Iterations) {
13679       Est = UseOneConstNR ?
13680         BuildRsqrtNROneConst(Op, Est, Iterations) :
13681         BuildRsqrtNRTwoConst(Op, Est, Iterations);
13682     }
13683     return Est;
13684   }
13685
13686   return SDValue();
13687 }
13688
13689 /// Return true if base is a frame index, which is known not to alias with
13690 /// anything but itself.  Provides base object and offset as results.
13691 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
13692                            const GlobalValue *&GV, const void *&CV) {
13693   // Assume it is a primitive operation.
13694   Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
13695
13696   // If it's an adding a simple constant then integrate the offset.
13697   if (Base.getOpcode() == ISD::ADD) {
13698     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
13699       Base = Base.getOperand(0);
13700       Offset += C->getZExtValue();
13701     }
13702   }
13703
13704   // Return the underlying GlobalValue, and update the Offset.  Return false
13705   // for GlobalAddressSDNode since the same GlobalAddress may be represented
13706   // by multiple nodes with different offsets.
13707   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
13708     GV = G->getGlobal();
13709     Offset += G->getOffset();
13710     return false;
13711   }
13712
13713   // Return the underlying Constant value, and update the Offset.  Return false
13714   // for ConstantSDNodes since the same constant pool entry may be represented
13715   // by multiple nodes with different offsets.
13716   if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
13717     CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
13718                                          : (const void *)C->getConstVal();
13719     Offset += C->getOffset();
13720     return false;
13721   }
13722   // If it's any of the following then it can't alias with anything but itself.
13723   return isa<FrameIndexSDNode>(Base);
13724 }
13725
13726 /// Return true if there is any possibility that the two addresses overlap.
13727 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
13728   // If they are the same then they must be aliases.
13729   if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
13730
13731   // If they are both volatile then they cannot be reordered.
13732   if (Op0->isVolatile() && Op1->isVolatile()) return true;
13733
13734   // Gather base node and offset information.
13735   SDValue Base1, Base2;
13736   int64_t Offset1, Offset2;
13737   const GlobalValue *GV1, *GV2;
13738   const void *CV1, *CV2;
13739   bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
13740                                       Base1, Offset1, GV1, CV1);
13741   bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
13742                                       Base2, Offset2, GV2, CV2);
13743
13744   // If they have a same base address then check to see if they overlap.
13745   if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
13746     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
13747              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
13748
13749   // It is possible for different frame indices to alias each other, mostly
13750   // when tail call optimization reuses return address slots for arguments.
13751   // To catch this case, look up the actual index of frame indices to compute
13752   // the real alias relationship.
13753   if (isFrameIndex1 && isFrameIndex2) {
13754     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
13755     Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
13756     Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
13757     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
13758              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
13759   }
13760
13761   // Otherwise, if we know what the bases are, and they aren't identical, then
13762   // we know they cannot alias.
13763   if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
13764     return false;
13765
13766   // If we know required SrcValue1 and SrcValue2 have relatively large alignment
13767   // compared to the size and offset of the access, we may be able to prove they
13768   // do not alias.  This check is conservative for now to catch cases created by
13769   // splitting vector types.
13770   if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
13771       (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
13772       (Op0->getMemoryVT().getSizeInBits() >> 3 ==
13773        Op1->getMemoryVT().getSizeInBits() >> 3) &&
13774       (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
13775     int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
13776     int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
13777
13778     // There is no overlap between these relatively aligned accesses of similar
13779     // size, return no alias.
13780     if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
13781         (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
13782       return false;
13783   }
13784
13785   bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
13786                    ? CombinerGlobalAA
13787                    : DAG.getSubtarget().useAA();
13788 #ifndef NDEBUG
13789   if (CombinerAAOnlyFunc.getNumOccurrences() &&
13790       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
13791     UseAA = false;
13792 #endif
13793   if (UseAA &&
13794       Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
13795     // Use alias analysis information.
13796     int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
13797                                  Op1->getSrcValueOffset());
13798     int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
13799         Op0->getSrcValueOffset() - MinOffset;
13800     int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
13801         Op1->getSrcValueOffset() - MinOffset;
13802     AliasAnalysis::AliasResult AAResult =
13803         AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(),
13804                                          Overlap1,
13805                                          UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
13806                  AliasAnalysis::Location(Op1->getMemOperand()->getValue(),
13807                                          Overlap2,
13808                                          UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
13809     if (AAResult == AliasAnalysis::NoAlias)
13810       return false;
13811   }
13812
13813   // Otherwise we have to assume they alias.
13814   return true;
13815 }
13816
13817 /// Walk up chain skipping non-aliasing memory nodes,
13818 /// looking for aliasing nodes and adding them to the Aliases vector.
13819 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
13820                                    SmallVectorImpl<SDValue> &Aliases) {
13821   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
13822   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
13823
13824   // Get alias information for node.
13825   bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
13826
13827   // Starting off.
13828   Chains.push_back(OriginalChain);
13829   unsigned Depth = 0;
13830
13831   // Look at each chain and determine if it is an alias.  If so, add it to the
13832   // aliases list.  If not, then continue up the chain looking for the next
13833   // candidate.
13834   while (!Chains.empty()) {
13835     SDValue Chain = Chains.back();
13836     Chains.pop_back();
13837
13838     // For TokenFactor nodes, look at each operand and only continue up the
13839     // chain until we find two aliases.  If we've seen two aliases, assume we'll
13840     // find more and revert to original chain since the xform is unlikely to be
13841     // profitable.
13842     //
13843     // FIXME: The depth check could be made to return the last non-aliasing
13844     // chain we found before we hit a tokenfactor rather than the original
13845     // chain.
13846     if (Depth > 6 || Aliases.size() == 2) {
13847       Aliases.clear();
13848       Aliases.push_back(OriginalChain);
13849       return;
13850     }
13851
13852     // Don't bother if we've been before.
13853     if (!Visited.insert(Chain.getNode()).second)
13854       continue;
13855
13856     switch (Chain.getOpcode()) {
13857     case ISD::EntryToken:
13858       // Entry token is ideal chain operand, but handled in FindBetterChain.
13859       break;
13860
13861     case ISD::LOAD:
13862     case ISD::STORE: {
13863       // Get alias information for Chain.
13864       bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
13865           !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
13866
13867       // If chain is alias then stop here.
13868       if (!(IsLoad && IsOpLoad) &&
13869           isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
13870         Aliases.push_back(Chain);
13871       } else {
13872         // Look further up the chain.
13873         Chains.push_back(Chain.getOperand(0));
13874         ++Depth;
13875       }
13876       break;
13877     }
13878
13879     case ISD::TokenFactor:
13880       // We have to check each of the operands of the token factor for "small"
13881       // token factors, so we queue them up.  Adding the operands to the queue
13882       // (stack) in reverse order maintains the original order and increases the
13883       // likelihood that getNode will find a matching token factor (CSE.)
13884       if (Chain.getNumOperands() > 16) {
13885         Aliases.push_back(Chain);
13886         break;
13887       }
13888       for (unsigned n = Chain.getNumOperands(); n;)
13889         Chains.push_back(Chain.getOperand(--n));
13890       ++Depth;
13891       break;
13892
13893     default:
13894       // For all other instructions we will just have to take what we can get.
13895       Aliases.push_back(Chain);
13896       break;
13897     }
13898   }
13899
13900   // We need to be careful here to also search for aliases through the
13901   // value operand of a store, etc. Consider the following situation:
13902   //   Token1 = ...
13903   //   L1 = load Token1, %52
13904   //   S1 = store Token1, L1, %51
13905   //   L2 = load Token1, %52+8
13906   //   S2 = store Token1, L2, %51+8
13907   //   Token2 = Token(S1, S2)
13908   //   L3 = load Token2, %53
13909   //   S3 = store Token2, L3, %52
13910   //   L4 = load Token2, %53+8
13911   //   S4 = store Token2, L4, %52+8
13912   // If we search for aliases of S3 (which loads address %52), and we look
13913   // only through the chain, then we'll miss the trivial dependence on L1
13914   // (which also loads from %52). We then might change all loads and
13915   // stores to use Token1 as their chain operand, which could result in
13916   // copying %53 into %52 before copying %52 into %51 (which should
13917   // happen first).
13918   //
13919   // The problem is, however, that searching for such data dependencies
13920   // can become expensive, and the cost is not directly related to the
13921   // chain depth. Instead, we'll rule out such configurations here by
13922   // insisting that we've visited all chain users (except for users
13923   // of the original chain, which is not necessary). When doing this,
13924   // we need to look through nodes we don't care about (otherwise, things
13925   // like register copies will interfere with trivial cases).
13926
13927   SmallVector<const SDNode *, 16> Worklist;
13928   for (const SDNode *N : Visited)
13929     if (N != OriginalChain.getNode())
13930       Worklist.push_back(N);
13931
13932   while (!Worklist.empty()) {
13933     const SDNode *M = Worklist.pop_back_val();
13934
13935     // We have already visited M, and want to make sure we've visited any uses
13936     // of M that we care about. For uses that we've not visisted, and don't
13937     // care about, queue them to the worklist.
13938
13939     for (SDNode::use_iterator UI = M->use_begin(),
13940          UIE = M->use_end(); UI != UIE; ++UI)
13941       if (UI.getUse().getValueType() == MVT::Other &&
13942           Visited.insert(*UI).second) {
13943         if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
13944           // We've not visited this use, and we care about it (it could have an
13945           // ordering dependency with the original node).
13946           Aliases.clear();
13947           Aliases.push_back(OriginalChain);
13948           return;
13949         }
13950
13951         // We've not visited this use, but we don't care about it. Mark it as
13952         // visited and enqueue it to the worklist.
13953         Worklist.push_back(*UI);
13954       }
13955   }
13956 }
13957
13958 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
13959 /// (aliasing node.)
13960 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
13961   SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
13962
13963   // Accumulate all the aliases to this node.
13964   GatherAllAliases(N, OldChain, Aliases);
13965
13966   // If no operands then chain to entry token.
13967   if (Aliases.size() == 0)
13968     return DAG.getEntryNode();
13969
13970   // If a single operand then chain to it.  We don't need to revisit it.
13971   if (Aliases.size() == 1)
13972     return Aliases[0];
13973
13974   // Construct a custom tailored token factor.
13975   return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
13976 }
13977
13978 /// This is the entry point for the file.
13979 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
13980                            CodeGenOpt::Level OptLevel) {
13981   /// This is the main entry point to this class.
13982   DAGCombiner(*this, AA, OptLevel).Run(Level);
13983 }